Reputation: 1142
I have several checkboxes and a button inside a panel, that is inside a tabPage, inside a WinForm C# application.
What I am trying to do is making sure at least one checkbox is checked so enable the button to be clickable, if not the button will be disabled (gray display non-clickable).
I tried this (in Form_Load
event) but it didn't work:
int counter = 0;
foreach (Control p in tabPage1.Controls)
{
if (p is Panel)
{
foreach (Control c in panel1.Controls)
{
if (c is CheckBox)
{
if (((CheckBox)c).Checked)
{
counter++;
}
if (counter < 1)
{
button1.Enabled = false;
}
else
{
button1.Enabled = true;
}
}
}
}
}
It's either because I am using the wrong event or the wrong place to put the code, or the code itself isn't correct, can anyone take a look please?
Upvotes: 2
Views: 4202
Reputation: 1
Remove this part you never use "p" variable in your code below...
foreach(Control p in tabPage1.Controls)
{
if (p is Panel)
{
int counter = 0;
foreach(Control c in panel1.Controls)
{
if (c is CheckBox)
{
if (((CheckBox)c).Checked)
{
counter++;
}
if (counter < 1) {
button1.Enabled = false;
}
else {
button1.Enabled = true;
}
}
}
Upvotes: 0
Reputation: 2970
This code should be run in two places:
Load
event, after you've loaded the checkboxes with any saved valuesCheckedChanged
event handlers, so the button state is updated as checkboxes are checkedUpvotes: 1
Reputation: 65069
You can do something like this (note.. your specific loops are redundant.. you know the name of the container.. why loop searching for it?)
if (panel1.Controls.OfType<CheckBox>().Any(x => x.Checked)) {
// at least one is checked..
Upvotes: 7