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.
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!);
}
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; }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With