在单独的面板中配对单选按钮

时间:2015-10-20 13:04:54

标签: c# winforms visual-studio radio-button controls

我有一个Windows窗体应用程序,它在窗体中显示一些用户控件。每个用户控件都有一个单选按钮。是否可以手动配对单选按钮,以便只能同时选择其中一个?我的另一个选择是在单击单选按钮时检查每个单选按钮,以便取消选中所有其他单选按钮。

1 个答案:

答案 0 :(得分:1)

        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);
    }
}