Maiko Kingma
Maiko Kingma

Reputation: 939

pair radio buttons in seperate panels

I have a windows forms applications which shows some user controls in the form. Each user control has a radio button. Is it possible to manually pair the radio buttons so only one of them can be selected at the same time? My other option would be to check each radio button when a radio button is clicked so that all other radio buttons are unchecked.

Upvotes: 2

Views: 779

Answers (1)

Loathing
Loathing

Reputation: 5266

        RadioButton rb1 = new RadioButton { Text = "RB1" };
        RadioButton rb2 = new RadioButton { Text = "RB2" };
        RadioButtonGroup rgb = new RadioButtonGroup(rb1, rb2);

        foreach (RadioButton rb in new [] { rb1, rb2 }) {
            Form f = new Form { Text = rb.Text };
            f.Controls.Add(rb);
            f.Show();
            rb.CheckedChanged += delegate {
                MessageBox.Show(rb.Text + ": " + rb.Checked);
            };
        }



private class RadioButtonGroup {
    RadioButton[] radioButtons = null;
    public RadioButtonGroup(params RadioButton[] radioButtons) {
        this.radioButtons = radioButtons;
        foreach (var rb in radioButtons) {
            rb.AutoCheck = false;
            rb.Click += rb_Click;
        }
    }

    void rb_Click(object sender, EventArgs e) {
        foreach (RadioButton rb in radioButtons)
            rb.Checked = (rb == sender);
    }
}

Upvotes: 2

Related Questions