septaug
septaug

Reputation: 61

radiobuttons on different tabcontrol stay selected

Please read de question as it´s not a duplicate. I have a winforms app i C# witch has a tabcontrol with 3 tabs. Each tab has 4 radiobuttons. If i run the app, the radio buttons work fine within the same tab, but when i select another tab the selection remains in the first tab. I tried to clear all checked radiobuttons when changing tabs but for some reason it does not work. The code is use is:

private void UncheckLayouts(TabPage activePage)
{
    foreach (Control control in tabControl1.Controls)
    {
        if (control is RadioButton)
        {
            RadioButton rb = control as RadioButton;
            rb.Checked = false;
        }
    }
}

private void radioButton1_Click(object sender, EventArgs e)
{
    UncheckLayouts(tabControl1.SelectedTab);
}

private void radioButton2_Click(object sender, EventArgs e)
{
    UncheckLayouts(tabControl1.SelectedTab);
}
...

I tried like this too:

private void tabControl1_Deselecting(object sender, TabControlCancelEventArgs e) {
    foreach (var ctrl in e.TabPage.Controls) {
         if (ctrl is RadioButton) {
             RadioButton tb = ctrl as RadioButton;
             rb.Checked = false;
         }
    }
}

EDIT: new code.

public Form2()
{
    InitializeComponent();
    tabControl1.Selected += TabControl1_Selected;
}
private void TabControl1_Selected(object sender, TabControlCancelEventArgs e)
{
    foreach (var ctrl in e.TabPage.Controls)
    {
        if (ctrl is RadioButton)
        {
            RadioButton tb = ctrl as RadioButton;
            tb.Checked = false;
        }
    }
}

But no solution works. All radiobuttons were added to each tab with the designer.

Can anyone help please. Thanks in advance,

Upvotes: 0

Views: 315

Answers (1)

Nico Zhu
Nico Zhu

Reputation: 32775

You can use the following code,I tested that it was working fine

private void InitializeComponent(){
           ........
 tabControl1.Selected += TabControl1_Selected;
}



private void TabControl1_Selected(object sender, TabControlEventArgs e)
{
    foreach (var ctrl in e.TabPage.Controls)
    {
        if (ctrl is RadioButton)
        {
            RadioButton tb = ctrl as RadioButton;
            tb.Checked = false;
        }
    }
}

Upvotes: 1

Related Questions