使用字符串数组从多箱列表中获取信息

问题描述 投票:0回答:2

所以我有一个数组,在订单上有第一部分组合框。组合框保存数据(x1,x2,x3,x4),并命名为ketchupCount,mustardCount等...

我想要做的是使用数组normalCondoments array + Count生成正确的组合框名称,将SelectedIndex值设置为-1,这是未选中的。最终它将获取值,而不是设置它,并将其打印到字符串...

预期的代码应该读取ketchupCount.SelectedIndex

    string[] normalCondoments = { "ketchup", "mustard", "mayo", "ga",
                                  "lettuce", "tomato", "pickles", "onion" };
    foreach (var nCondoment in normalCondoments)
                {
                    string str = nCondoment + "Count";
                    MessageBox.Show("letter:" + nCondoment);
                    str.SelectedIndex = -1;
                }

我得到的错误是:

“字符串不包含'SelectedIndex'的选定定义,并且'SelectedIndex'没有可访问的扩展名,可以找到类型为'string'的第一个参数。”

VS没有给出一个修复,我看了看,但没有找到类似于这个错误的东西。提前致谢

c# string combobox selectedindexchanged assembly-references
2个回答
0
投票

您可以使用Container.Controls[]集合获取Control的引用。 该集合可以用Int32值或String索引,代表Control的名称。

在您的情况下,如果ComboBoxes都是Form的直接子代,那么您的代码可能是:

string[] normalCondoments = { "ketchup", "mustard", "mayo", "ga",
                              "lettuce", "tomato", "pickles", "onion" };

foreach (var nCondoment in normalCondoments) {
    (this.Controls[$"{nCondoment}Count"] as ComboBox).SelectedIndex = -1;
}

否则,将this替换为实际容器。

如果这些控件是不同容器的子控件,则需要找到它们。 在这种情况下,使用Controls集合的Find()方法,指定searchAllChildren

foreach (var nCondoment in normalCondoments) {
    var cbo = (this.Controls.Find($"{nCondoment}Count", true).FirstOrDefault() as ComboBox);
    if (cbo != null) cbo.SelectedIndex = -1;
}

0
投票

这不是javascript,你必须使用变量而不是它的名字

ketchupCount.SelectedIndex = -1;
mustardCount.SelectedIndex = -1;
mayoCount.SelectedIndex = -1;
gaCount.SelectedIndex = -1;
lettuceCount.SelectedIndex = -1;
tomatoCount.SelectedIndex = -1;
picklesCount.SelectedIndex = -1;
onionCount.SelectedIndex = -1;

或者创建一个数组来保存它们

var normalCondoments = new multibox[] {ketchupCount, mustardCount, mayoCount, gaCount,
     lettuceCount, tomatoCount, picklesCount, onionCount};
foreach(var nCondoment in normalCondoments)
  nCondoment.SelectedIndex = -1;
© www.soinside.com 2019 - 2024. All rights reserved.