首页 > 解决方案 > 使用字符串数组从多框列表中获取信息

问题描述

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

我想要做的是使用数组 normalCondoments 数组 + 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#stringcomboboxselectedindexchangedassembly-references

解决方案


您可以使用Container.Controls[]集合获取控件的引用。
这个集合可以由一个Int32值或一个String表示控件名称的索引。

在您的情况下,如果 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;
}

推荐阅读