1

I am implementing a single event handler to handle CheckedChanged event for all radioButtons on the Panel. ( Event handler for groupBox with radioButtons in C#, Which Radio button in the group is checked? )

I was waiting that when I switch a radioButton there are 2 events: one called from unchecked radioButton, and one called from a checked one.

public Form1()
{
    Panel createToolPanel()
    {
        radioButton1.CheckedChanged += toolPanel_CheckedChanged;
        radioButton2.CheckedChanged += toolPanel_CheckedChanged;
        radioButton3.CheckedChanged += toolPanel_CheckedChanged;
        // ...
    }

    void toolPanel_CheckedChanged (object sender, EventArgs e)
    {
        var rb = (RadioButton)sender;

        if (rb.Checked == false)
            return;

        switch(rb.Name)
        {
            // Do stuff
        }
    }

But instead every time I switch any of radioButtons the sender is always the first radioButton.

sender: radioButton1
sender: radioButton1

What is more important, when I switch from 2nd to 3rd radioButton (or from 3rd to 2nd), no event occurs at all. I don't understand why is it happening..

I also tried to change adding event handler code like this:

radioButton1.CheckedChanged += new EventHandler(toolPanel_CheckedChanged);
radioButton2.CheckedChanged += new EventHandler(toolPanel_CheckedChanged);
radioButton3.CheckedChanged += new EventHandler(toolPanel_CheckedChanged);

But it does not helped.

Shamil
  • 13
  • 5
  • How are you adding these buttons to the panel? I just checked in a simple form and it's behaving as expected (i. e. two events are fired when a button changed). I suspect that `radioButton1`, `radioButton2` and `radioButton3` all refer to the same control. – germi Jan 23 '20 at 10:17
  • Same as @germi, cannot reproduce. It works perfectly on my end. – Kilazur Jan 23 '20 at 10:18
  • @germi, I am adding them all to a panel `panel.Controls.Add(radioButton1)` – Shamil Jan 23 '20 at 10:30
  • I'm thinking that the three variables are all referring to the same `RadioButton`. Could you check that? That would explain your observed behavior. – germi Jan 23 '20 at 10:31
  • I found the problem. Actually there was an error that all the events where added to the first radioButton due to the long names of my buttons. Quite silly. You are right @germi. Thank you! – Shamil Jan 23 '20 at 10:33

0 Answers0