首页 > 解决方案 > 如何将不同面板中存在的单选按钮分组为一个组?

问题描述

我必须将RadioButton存在于不同 Panels 中的 s 分组为一个。Sa,y 例如,我有一个RadioButton名为radBtn1onpanel1和on 。现在我想将所有这些单选按钮分组为一个以便一次只检查一个。radBtn2radBtn2panel2 RadioButton

标签: c#winformsradio-button

解决方案


我们可以尝试手动RadioButton取消选中s 。让我们为所有感兴趣的人分配事件处理程序:RadioButtons_CheckedChanged RadioButtons

private void RadioButtons_CheckedChanged(object sender, EventArgs e) {
  // If we have a RadioButton Checked 
  if (sender is RadioButton current && current.Checked) {
    // We should remove Check from the rest RadioButtons:
    var rest = new Control[] { panel1, panel2} 
      .SelectMany(ctrl => ctrl             // all radiobuttons on panel1, panel2
         .Controls
         .OfType<RadioButton>())
      .Where(button => button != current); // don't touch current it should stay checked

    foreach (var button in rest)
      button.Checked = false;
  }
}

推荐阅读