【问题标题】:Using a string array to get information from a list of multiboxes使用字符串数组从多框列表中获取信息
【发布时间】:2019-09-18 16:34:47
【问题描述】:

所以我有一个数组,其中包含订单表单上组合框的第一部分。组合框包含数据(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' 的选定定义,并且无法找到接受 'string' 类型的第一个参数的 'SelectedIndex' 的可访问扩展。”

VS 没有解决这个问题,我看了又看,但没有发现类似这个错误的东西。提前致谢

【问题讨论】:

  • 什么是多选框?你指的是组合框吗?一个列表框?你能指定你正在使用的平台吗?您是否尝试将对象的引用与设置为其名称的字符串一起使用?
  • 你指的是<html:multibox>吗?
  • 我很抱歉它是组合框,在上面进行编辑以反映正确的术语

标签: c# string combobox selectedindexchanged assembly-references


【解决方案1】:

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

在您的情况下,如果组合框都是表单的直接子级,您的代码可能是:

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;
}

【讨论】:

  • 你Jimi是个天才,这已经让我发疯了好几天,我会稍微发布工作代码
  • 我确实必须添加容器名称而不是“this”codeint answer; foreach (var nCondoment in normalCondoments) { answer = (nCondomentsContainer.Controls[$"{nCondoment}Count"] as ComboBox).SelectedIndex;字符串str = nCondoment +“计数”; if (answer > -1) { MessageBox.Show(nCondoment +" " + (answer+1)); rCondoments = rCondoments + nCondoment + " " + (answer + 1) + "\n"; } }
【解决方案2】:

这不是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;

【讨论】:

  • 我不需要一个数组来保存它们,我只需要显示它们。问题是,我不能使用变量字符串来循环遍历所有 8 个,我尝试调用 string[] normalCondoments = {ketchupCount, mustardCount, blah} 它仍然作为字符串读取。
猜你喜欢
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
  • 2018-09-14
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多