简体   繁体   中英

How can I iterate all ComboBoxes controls with a loop in C#?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM