Only one checkbox to be selected

后端 未结 5 1664
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 19:15

I would like to only have single checkbox selected at a time. My program reads from a textfile and creates checkboxes according to how many \"answers\" there are in the text

5条回答
  •  隐瞒了意图╮
    2021-01-14 19:41

    1. Put the checkbox inside the groupbox control.
    2. Loop the control enclosed on the groupbox
    3. Find the checkbox name in the loop, if not match make the checkbox unchecked else checked the box.

    See Sample code:

    //Event CheckedChanged of checkbox:
    private void checkBox6_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox cb = (CheckBox)sender;
        if (cb.CheckState == CheckState.Checked)
        {
            checkboxSelect(cb.Name);
        }
        }
    
    //Function that will check the state of all checkbox inside the groupbox
    private void checkboxSelect(string selectedCB)
    {
        foreach (Control ctrl in groupBox1.Controls)
        {
            if (ctrl.Name != selectedCB)
            {
                CheckBox cb = (CheckBox)ctrl;
                cb.Checked = false;
            }
        }
    }
    

提交回复
热议问题