1

I have list of 20 combo box NAME: combobox1z to combobox20z. I want to set text of those combobox via list and for loop, and don't know if it is possible like:

for (int i = 1; i < 21; i++)
{
    comboxbox[i]z.Text = stringlist[i];
}
Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
Jackie
  • 9
  • 5
  • 2
    `WinForms`, `WPF` or...? – Trevor Apr 03 '20 at 19:46
  • I don't really like to duplicate the same code 20 times because of the combox[i]z name is unique and can't put in loop. – Jackie Apr 03 '20 at 19:46
  • 6
    `for (int i = 1; i < 21; i++) { this.Controls["comboxbox" + i.ToString() + "z"]?.Text = stringlist[i]; }` quick and dirty if using `WinForms`. – Trevor Apr 03 '20 at 19:48
  • For winforms look at [this post](https://stackoverflow.com/questions/1536739/get-a-windows-forms-control-by-name-in-c-sharp) – Michał Turczyn Apr 03 '20 at 19:52
  • 1
    Does this answer your question? [Get a Windows Forms control by name in C#](https://stackoverflow.com/questions/1536739/get-a-windows-forms-control-by-name-in-c-sharp) – Michał Turczyn Apr 03 '20 at 19:53
  • yes, WinForm. let me try your code. but how is it dirty you mean ? – Jackie Apr 03 '20 at 19:55
  • @Çöđěxěŕ - That would only work if the ComboBoxes aren't inside another control. You may to drill down recursively to get all the ComboBoxes. – Frank Ball Apr 03 '20 at 20:04
  • @Frank Ball of course, but we dont have that information to know that. – Trevor Apr 03 '20 at 20:07
  • 1
    @Jackie there's other ways to do it and its a general response enough to get you started. For example, are these combobox's in other controls, if so, you would need recursion to dig down. – Trevor Apr 03 '20 at 20:15
  • yes @Çöđěxěŕ, i tried your code, it works properly. but my case is the combo box in inside the groupbox and it not work anymore. Could you show me the general way to get it ? – Jackie Apr 04 '20 at 07:07
  • corrected, @FrankBall. my case is the ComboBoxes inside the GroupBox. is there the general way to solve it ? – Jackie Apr 04 '20 at 07:07

1 Answers1

0

**

try this

**

for (int i = 1; i < 21; i++)

{

ComboBox comboBox = new ComboBox();

comboBox = this.Controls.Find("comboxbox" + i.ToString()+"Z", false)[0];

   for (int y = 1; y < 21; y++)

   {

       comboBox1.Items.Add (stringlist[y]);

   }

}