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