If one checkbox is checked, set the other to unchecked

前端 未结 9 1658
Happy的楠姐
Happy的楠姐 2021-01-13 10:06

I have two checkboxes on my form; chkBuried and chkAboveGround. I want to set it up so if one is checked, the other is unchecked. How can I

9条回答
  •  旧巷少年郎
    2021-01-13 10:55

    List groupOfCheckBoxes = new List();
    void InitFunction() {
        groupOfCheckBoxes.Add(checkbox1);
        groupOfCheckBoxes.Add(checkbox2);
        groupOfCheckBoxes.Add(checkbox3);
        foreach (CheckBox cb in groupOfCheckBoxes)
         cb.Click += checkbox_Click
    }
    void checkbox_Click(object sender, EventArgs e) 
    {
     foreach (CheckBox cb in groupOfCheckBoxes) {
      cb.IsChecked = cb == sender;
     }
    }
    

    However I would suggest radio boxes as well. The code above is untested and may have some typos

提交回复
热议问题