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
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;
}
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;
}
}
}
I think you are looking for Radio Buttons.
If you are insistent on using checkboxes then change your event to CheckedChanged as this will be more accurate. Check boxes can unfortunately be clicked without checking themselves!
Try using an external Bool variable to know when the CheckBox was changed "automatically"
CheckBox checkBox1;
CheckBox checkBox2;
Bool changed = false; //This one
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (!changed)
{
if (checkBox2.Checked)
{
changed = true;
checkBox2.Checked = false;
}
}
else
{
changed = false;
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (!changed)
{
if (checkBox1.Checked)
{
changed = true;
checkBox1.Checked = false;
}
}
else
{
changed = false;
}
}
Ok this should do what you want to do, either onClick or on CheckChanged but the answer is from CheckChanged.
Put this in the chk_CheckChanged event and add the chk_CheckChanged event to each Checkbox you add.
CheckBox tmp = (CheckBox)sender;
foreach (CheckBox c in flowLayoutPanel1.Controls)
{
c.CheckedChanged -= chk_CheckedChanged;
c.Checked = false;
}
tmp.Checked = true;
foreach (CheckBox c in flowLayoutPanel1.Controls)
{
c.CheckedChanged += chk_CheckedChanged;
}