Reputation: 616
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";
}
Upvotes: 0
Views: 2882
Reputation: 172220
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";
}
Upvotes: 1
Reputation: 843
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!";
}
Upvotes: 2
Reputation: 101681
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";
}
Upvotes: 2