仅选中一个复选框 [英] Only one checkbox to be selected
本文介绍了仅选中一个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一次只能选择一个复选框。我的程序从文本文件中读取并根据文本文件中有多少答案创建复选框。
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 textfile.
有人知道代码有什么问题吗?
Does anyone know what is wrong with the code?
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; }
}
}
}
}
推荐答案
实现您想要的东西是如此简单,但是奇怪也是如此:
It's so simple to achieve what you want, however it's also so strange:
//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;
}
这篇关于仅选中一个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文