How can I iterate all ComboBoxes controls with a l

2019-03-04 03:38发布

问题:

I have some comboBoxes on a winform (for example 10) in C# named: comboBox1, coboBox2 and comboBoxN. How can I access all of them in a for loop like this:

for(int i = 0; i < 10; i++)
{
    comboBox[i].text = "Hello world";
}

回答1:

You can use OfType method

var comboBoxes =  this.Controls
                  .OfType<ComboBox>()
                  .Where(x => x.Name.StartsWith("comboBox"));

foreach(var cmbBox in comboBoxes)
{
    cmbBox.Text = "Hello world";
}


回答2:

You can access to all the combobox in a form that way (assuming this is a form):

     List<ComboBox> comboBoxList = this.Controls.OfType<ComboBox>();

Then you just need to iterate over them

     foreach (ComboBox comboBox in comboBoxList)
     {
        comboBox.Text = "Hello world!";
     }


回答3:

Forms have a Controls property, which returns a collection of all controls and which can be indexed by the name of the control:

for(int i = 0; i < 10; i++)
{
    var comboBox = (ComboBox)this.Controls["comboBox" + i.ToString()];
    comboBox.text = "Hello world";
}