foreach (ComboBox a in Form1.ActiveForm.Controls)
{
  MessageBox.Show("hello");
}

Hi, i want to add same items to all ComboBoxes, expect one. The part of my code is here. The problem is foreach loop never fire. I never see the MessageBox which is saying "hello". What is wrong in my code?

Thanks.

Form1.ActiveForm.Controls is a collection of all controls on the active form. These could be any control type - TextBox, Label, Panel, not just ComboBox.
Try this.

foreach (Control a in Form1.ActiveForm.Controls) //<-- loop object is Control type.
{
    if (a is ComboBox) //<-- test if loop object is a ComboBox
    {
        MessageBox.Show("hello"); // do something
    }
}
foreach (Control a in this.Controls)
{
   if (a is ComboBox)
   {
      a.Items.Add(" ");
      a.Items.Add("F1");
   }
}

Thanks, now MessageBox triggered. But i cant adding items to ComboBox. Items are giving following error:

'System.Windows.Forms.Control' does not contain a definition for 'Items' and no extension method 'Items' accepting a first argument of type 'System.Windows.Forms.Control' could be found (are you missing a using directive or an assembly reference?)

Your also need brackets around the cast item.

((ComboBox)a).Items.Add();

Or use another variable

foreach (Control a in Form1.ActiveForm.Controls)
{
    ComboBox combo = a as ComboBox; //<-- converts a to ComboBox type or null
    if (combo !=null) // if not null then 'a' was a ComboBox
    {
        combo.Items.Add("a");
        combo.Items.Add("b");
    }
}

Edited 6 Years Ago by nick.crane: Added alternate method, Added comments to code

Now working perfect, thanks.

Edited 6 Years Ago by wlalth: n/a

This question has already been answered. Start a new discussion instead.