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.

Recommended Answers

All 6 Replies

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?)

Cast (ComboBox) in front of the a item.

(ComboBox)a.Items.Add();

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");
    }
}

Now working perfect, thanks.

If solved, then please mark the thread solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.