C
C#9mo ago
Ethan

✅ Help with windows forms check uncheck thing

I want it to be where only 1 checkbox can be checked at a time, I tried this but it is not working, any help?
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if(checkBox2.Checked && (checkBox3.Checked || checkBox4.Checked || checkBox5.Checked))
{
checkBox2.Checked = false;
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if(checkBox2.Checked && (checkBox3.Checked || checkBox4.Checked || checkBox5.Checked))
{
checkBox2.Checked = false;
}
}
6 Replies
oke
oke9mo ago
rather than going through each checkbox and checking its state, you can just set any box that isnt the one just clicked, and make them unchecked this solution kind of assumes you mean every box in the form
private void anyCheckBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox clickedCheckbox = (CheckBox)sender;

foreach (Control control in this.Controls)
if (control is CheckBox && control != clickedCheckbox)
((CheckBox)control).Checked = false;
}
private void anyCheckBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox clickedCheckbox = (CheckBox)sender;

foreach (Control control in this.Controls)
if (control is CheckBox && control != clickedCheckbox)
((CheckBox)control).Checked = false;
}
Ethan
EthanOP9mo ago
that makes sense, and yeah i do want it for all the checkboxes. Thank you very much if i wanted to exclude 1 checkbox how could i do that? i did forget about 1
oke
oke9mo ago
if you need this on specific boxes, your best bet would be to assign references to them in an array via the classes constructor
private CheckBox[] boxes;
public Form1()
{
InitializeComponent();
boxes = [
// Possible checkbox
// checkBox1
checkBox2,
checkBox3,
checkBox4,
checkBox5
]
}

private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
foreach (var box in boxes)
box.Checked = false;

((CheckBox)sender).Checked = true;
}
private CheckBox[] boxes;
public Form1()
{
InitializeComponent();
boxes = [
// Possible checkbox
// checkBox1
checkBox2,
checkBox3,
checkBox4,
checkBox5
]
}

private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
foreach (var box in boxes)
box.Checked = false;

((CheckBox)sender).Checked = true;
}
Ethan
EthanOP9mo ago
thank you
oke
oke9mo ago
yw when your ready, you can use /close to $close this thread
MODiX
MODiX9mo ago
Use the /close command to mark a forum thread as answered
Want results from more Discord servers?
Add your server