2
votes

I am having 40 combo-box in my win-form application, I want to check at end on button click that all the combo-box value has been entered i.e no combo-box value has been selected empty

i am trying below code using for each loop but cant find success

foreach (Control c in this.Controls)
{
      if (c is ComboBox)
      {
           ComboBox textBox = c as ComboBox;
           if (textBox.SelectedValue==string.Empty)
           {
               MessageBox.Show("please fill all fields");
           }
      }
}

so how to achieve this validation in simple lines of codes

2
this.control will only provide you access to the controls in Form but if your Combos are nested in some Panel or etc. it will skipyogi
i am having combobox in tabcontrols of winform pageAdi

2 Answers

3
votes

Try to use linq and a recursion:

var isAnyEmpty = ScanForControls<ComboBox>(this)
   .Where(x => x.SelectedIndex < 0)
   .Any();

if (isAnyEmpty)
    MessageBox.Show("please fill all fields");

And recursion search:

public IEnumerable<T> ScanForControls<T>(Control parent) where T : Control
{
    if (parent is T)
        yield return (T)parent;

    foreach (Control child in parent.Controls)
    {
        foreach (var child2 in ScanForControls<T>(child))
            yield return (T)child2;
    }
}
0
votes

To make sure that you check each & every ComboBox in your Form you will have to iterate over each control in you Form, Try this for that.

private void button1_Click(object sender, EventArgs e)
{
   foreach (Control c in this.Controls)
   {
      if (c is ComboBox)
      {
         ComboBox textBox = c as ComboBox;
         if (textBox.SelectedValue == null)
         {
            MessageBox.Show("please fill all fields");
            break;
         }
       }
       else
          recursiveComboboxValidator(c);
    }
}

void recursiveComboboxValidator(Control cntrl)
{
    foreach (Control c in cntrl.Controls)
    {
       if (c is ComboBox)
       {
           ComboBox textBox = c as ComboBox;
           if (textBox.SelectedValue == null)
           {
                MessageBox.Show("please fill all fields");
                break;
           }
        }
        else
            recursiveComboboxValidator(c);
     }
}