C# How to prevent the event handler assigned to multiple controls being called twice? -


i'm new c# , having trouble event handler in windows forms application. have multiple radio buttons created during runtime (stored in buttonz list), , have same event handler assigned them.

in foreach loop:

buttonz.add(new radiobutton()); buttonz[buttonz.count - 1].checkedchanged += new eventhandler(radio_checked); 

below event handler:

private void radio_checked(object sender, eventargs e) {     radiobutton btn = (radiobutton)sender;     console.writeline("{0} radio checked!", btn.text); } 

the output is:

button1 radio checked! (1st button checked) button1 radio checked! (2nd button checked) button2 radio checked! button2 radio checked! (3rd button checked) button3 radio checked! 

so, event handler called when button unchecked either. how can prevent this? have read few questions complicated level therefore couldn't extract information need. explanatory answers more welcome. thanks.

the problem facing here event called a) when control checked , b) when control unchecked. hint for event called checkedchanged.

in event handler, need filter calls. cast sender checkbox , check 'checked' property:

private void radio_checked(object sender, eventargs e) {     //check if radio button. might checkbox!     if(sender radiobutton)     {         radiobutton btn = (radiobutton)sender;         if(btn.checked)             console.writeline("{0} radio checked!", btn.text);     } } 

Comments