0
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.

3
Contributors
6
Replies
8
Views
7 Years
Discussion Span
Last Post by nick.crane
1

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

2

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 by nick.crane: Added alternate method, Added comments to code

0

Now working perfect, thanks.

Edited by wlalth: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.