James Morrison
James Morrison

Reputation: 2122

Add items to combo Boxes while referring to the combo box name by a string in c# Windows form

Been searching high and low for the answer of how to do this! I basically have 26 combo boxes named comboBox1 - comboBox26 and want to use a for loop to add items to each box, so I'll need to refer to the comboBox as a string. Bit bad at explaining, here is the code I have so far;

for (int n = 1; n <= 26; n++)
{
      this.["comboBox"].Text.AddRange(new string[] 
             {"First Item", "second item", "third", "fourth", "fifth"}); 
}

so after the loop all 26 combo boxes should be populated with that string array. This and everything else I've tried throws an error and can't seem to find an answer, any help would be awesome!

thanks

Upvotes: 3

Views: 92

Answers (2)

Abid Zahid
Abid Zahid

Reputation: 21

you can use This:

var matches = this.Controls.Find("cmbname", true);

or

ComboBox cmb = (ComboBox)this.Controls.Find("cmbname" + i, false).FirstOrDefault();

Upvotes: 0

Shannon Holsinger
Shannon Holsinger

Reputation: 2361

use controls.Find:

for (int n = 1; n <= 26; n++)
{
    ComboBox c = Controls.Find("comboBox_"+n.ToString(),true)[0] as ComboBox;
    c.Items.AddRange(new string[] {"First Item", "second item", "third", "fourth", "fifth"});
}

This is assuming you've named your comboboxes comboBox_0 through comboBox_25

Upvotes: 5

Related Questions