c# - 使用字符串数组从多框列表中获取信息
问题描述
所以我有一个数组,它在订单表格上包含第一部分组合框。组合框保存数据(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 没有解决这个问题,我看了又看,但没有发现类似这个错误的东西。提前致谢
解决方案
您可以使用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;
}
推荐阅读
- batch-file - 是否有公开 start 命令搜索的路径的 API?
- typescript - 调度 thunk 动作创建者在 TypeScript 中不匹配
- reactjs - 一个人如何拥有指向不同 React.js 应用程序的链接菜单
- machine-learning - BatchNorm1d 需要二维输入?
- python - 如何从函数的闭包中访问/修改变量?
- c++ - 除数之和不大于数字时确定数字的因素,程序将不接受大于10000的限制
- reactjs - 如何在 redux-form 中使用自定义组件?
- python - AttributeError: 'super' object has no attribute '__getattr__' 在尝试将小部件添加到 Layout 的个性化 id 时
- flutter - 在 Flutter 中自定义应用栏,如 gmail 应用栏设计
- r - 无论绘图尺寸如何,都对 text() 和 legend() 使用恒定的垂直调整