使用C#中的不同父控件对Windows窗体Radiobutton进行分组

Jel*_*ela 10 c# radio-button winforms

我有一个Windows窗体应用程序,其中我有许多RadioButtons.这些RadioButton放置在FlowLayoutPanel中,它自动为我安排它们.直接添加到FlowLayoutPanel的所有RadioButton都被分组,这意味着我只能选择其中一个.但是,其中一些RadioButtons与TextBox配对,所以我可以在那里提供一些参数.但为了正确安排所有这些,我将一个Panel控件添加到FlowLayoutPanel,这样我就可以自己控制RadioButton和TextBox相对于彼此的对齐方式.

这些RadioButton现在有各自的Panel作为父控件,因此不再包含在与其他RadioButtons的无线电组中.我读到System.Web.UI命名空间中的RadioButtons 具有GroupName属性,但不幸的是他们的System.Windows.Forms对应物缺少此属性.有没有其他方法我可以组合这些单选按钮是我将不得不自己处理onClick事件?

谢谢,杰里

Tho*_*que 13

我担心你必须手动处理它......实际上并没有那么糟糕,你可以将所有RadioButton存储在一个列表中,并为所有这些使用单个事件处理程序:

private List<RadioButton> _radioButtonGroup = new List<RadioButton>();
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = (RadioButton)sender;
    if (rb.Checked)
    {
        foreach(RadioButton other in _radioButtonGroup)
        {
            if (other == rb)
            {
                continue;
            }
            other.Checked = false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)