如何遍历我拥有的所有组合框控件并将每个组合框的项目添加到列表中? [英] How can i loop over all comboBoxes controls i have and add the items of each comboBox to a List?
本文介绍了如何遍历我拥有的所有组合框控件并将每个组合框的项目添加到列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试过了:
var comboBoxes = this.Controls
.OfType<ComboBox>()
.Where(x => x.Name.StartsWith("comboBox"));
foreach (var cmbBox in comboBoxes)
{
CMBXWMICLASSES.AddRange(cmbBox.Items[
}
但是在循环内部,foreach 如何添加每个 ComboBox 的项目?
But inside the loop the foreach how do I add the Items of each ComboBox ?
这是一个工作代码:
在 form1 的顶部我做了:
In the top of form1 i did:
List<string> CMBXWMICLASSES = new List<string>();
然后我添加了一个递归处理所有控件及其子控件的方法:
Then i added a method that make recursively process all controls and their children:
public IEnumerable<Control> GetAll(Control control, Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl, type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
然后在构造函数中添加来自每个 ComboBox 的项目:
Then adding the items from each ComboBox in the constructor:
var c = GetAll(this, typeof(ComboBox));
foreach (ComboBox cc in c)
{
foreach (string ccc in cc.Items)
{
CMBXWMICLASSES.Add(ccc);
}
}
推荐答案
试试这个,
List<string> Items = new List<string>();
var comboBoxes = this.Controls
.OfType<ComboBox>()
.Where(x => x.Name.StartsWith("comboBox"));
foreach (var cmbBox in comboBoxes)
{
foreach (var cmbitem in cmbBox.Items)
{
Items.Add(cmbitem.ToString());
}
}
这篇关于如何遍历我拥有的所有组合框控件并将每个组合框的项目添加到列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文