C# 多个checkBox框里,只选一个,不可以多选

C# 如何实现, 多个checkBox框里,只选一个,不可以多选.

在C#中,可以使用CheckedChanged事件来实现多个CheckBox框中只能选择一个的功能。在事件处理程序中,首先需要遍历所有CheckBox框,然后将除了当前选择的CheckBox框以外的所有CheckBox框都设置为未选中状态。代码如下:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    CheckBox currentCheckBox = (CheckBox)sender;
    if (currentCheckBox.Checked)
    {
        foreach (Control c in this.Controls)
        {
            if (c is CheckBox && c != currentCheckBox)
            {
                ((CheckBox)c).Checked = false;
            }
        }
    }
}

这样的话,每个checkbox都要设置这个事件,可能会比较麻烦,如果是winform,可以考虑在统一的父容器中统一设置事件,减少代码量.

你可以在checkbox的CheckedChanged事件里自己写代码
但是为什么不直接用radiobutton呢,直接用单选框不香吗

望采纳!!!

CheckBox lastChecked;
private void chk_Click(object sender, EventArgs e) {
   CheckBox activeCheckBox = sender as CheckBox;
   if(activeCheckBox != lastChecked && lastChecked!=null) lastChecked.Checked = false;
   lastChecked = activeCheckBox.Checked ? activeCheckBox : null;
}

谢谢大家回复,问题一解决。