只能选择一个复选框

gri*_*n55 2 c# checkbox winforms

我想一次只选择一个复选框.我的程序从文本文件中读取并根据文本文件中有多少"答案"创建复选框.

有谁知道代码有什么问题?

public partial class Form1 : Form

    {
        string temp = "questions.txt";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            StreamReader sr = new StreamReader(temp);
            string line = "";
            List<string> enLista = new List<string>();
            while ((line = sr.ReadLine()) != null)
            {
                string[] myarray = line.Split('\r');
                enLista.Add(myarray[0]);


            }
            sr.Close();


            for (int i = 0; i < enLista.Count; i++)
            {
                if (enLista[i].Contains("?"))
                {
                    Label lbl = new Label();
                    lbl.Text = enLista[i].ToString();
                    lbl.AutoSize = true;
                    flowLayoutPanel1.Controls.Add(lbl);
                }
                else if (enLista[i] == "")
                {

                }
                else
                {
                    CheckBox chk = new CheckBox();
                    chk.Text = enLista[i].ToString();
                    flowLayoutPanel1.Controls.Add(chk);
                    chk.Click += chk_Click;
                }
            }

        }
        private void chk_Click(object sender, EventArgs e)
        {
            CheckBox activeCheckBox = sender as CheckBox;
            foreach (Control c in Controls)
            {
                CheckBox checkBox = c as CheckBox;
                if (checkBox != null)
                {
                    if (!checkBox.Equals(activeCheckBox))
                    { checkBox.Checked = !activeCheckBox.Checked; }
                    else
                    { checkBox.Checked = true; }
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

小智 7

我想你正在寻找收音机按钮.

如果您坚持使用复选框,请将事件更改为CheckedChanged,因为这样会更准确.不幸的是,可以点击复选框而不检查自己!

  • 然后你的标题是误导. (2认同)

Kin*_*ing 7

实现你想要的东西很简单,但它也很奇怪:

//We need this to hold the last checked CheckBox
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;
}
Run Code Online (Sandbox Code Playgroud)