简体   繁体   English

将项目添加到组合框,同时在 c# Windows 表单中通过字符串引用组合框名称

[英]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.我基本上有 26 个名为 comboBox1 - comboBox26 的组合框,并且想要使用 for 循环向每个框添加项目,因此我需要将组合框称为字符串。 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.所以在循环之后,所有 26 个组合框都应该用该字符串数组填充。 This and everything else I've tried throws an error and can't seem to find an answer, any help would be awesome!这和我尝试过的其他一切都会引发错误,似乎无法找到答案,任何帮助都会很棒!

thanks谢谢

use controls.Find :使用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这是假设您已将组合框命名为comboBox_0comboBox_25

you can use This:你可以使用这个:

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

or或者

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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