我想一次只選中一個複選框。我的程序從文本文件中讀取並根據文本文件中有多少「答案」創建複選框。只有一個複選框被選中
有人知道代碼有什麼問題嗎?
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; }
}
}
}
}
當然!它很簡單,當你看到代碼:)謝謝@王金 – grimsan55