C
C#8mo 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
oke8mo 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
Ethan8mo 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
oke8mo 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
Ethan8mo ago
thank you
oke
oke8mo ago
yw when your ready, you can use /close to $close this thread
MODiX
MODiX8mo ago
Use the /close command to mark a forum thread as answered
Want results from more Discord servers?
Add your server