Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a method where multiple controls are false in an "if" statement for C#?

What is the best way to simplify this (via method creation or otherwise):

if ((radioButton1.Checked == false) && (radioButton2.Checked == false) && (radioButton1.Checked == false) && ...more similar controls... && ((radioButton99.Checked == false))
{ 
    MessageBox.Show("Please select an option!);
}

Thank you for your consideration. Apologies for any inconvenience or grievances caused.

like image 481
Stoverflow Avatar asked Nov 20 '25 15:11

Stoverflow


2 Answers

You could put all those controls in a List and then check whether any of the controls in the list is checked. This can be done in several ways. Below examples of two of those.

Example using loop:

bool optionSelected = false;
foreach(var control in controls) // the List is in this case called controls
{
    if(control.Checked)
    {
        optionSelected = true;
    }
}
// Check the boolean

Example using System.Linq:

if(!controls.Any(c => c.Checked))
{
    MessageBox.Show("Please select an option!);
}
like image 165
Dnomyar96 Avatar answered Nov 22 '25 04:11

Dnomyar96


You need to add your controls into a public collection to simply iterate them. if you have a bunch of the same type controls, it's better to put them into a array in your form's constructor :

 CheckBox[] MyBoxes = new CheckBox[]{ check01, check02 , ... }
 // MyBoxes is filled at Form_Load and it's usable in throughout of the form 
 bool result = true;
 for(int i=0; i<MyBoxes.Length; i++)
 { 
       if (MyBoxes[i].Checked == false)
        {  result = false; break; } 
 }

another solution is to iterate whole controls on the form:

 bool result = true;
 for(int i=0; i<this.Controls.Count; i++)
 { 
    if (this.Controls[i] is CheckBox)
    {
        if ((this.Controls[i] as CheckBox).Checked == false)
        {  result = false; break; } 
    }
 }
like image 22
RezaNoei Avatar answered Nov 22 '25 06:11

RezaNoei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!