繁体   English   中英

从控件列表中检索下拉列表项

[英]Retrieving drop down list items from list of controls

我正在尝试从控件List中检索ListItemCollection List包含许多不同类型的控件DropDownListLabelTextBox

我想从原始控件List中包含的所有DropDownList控件中检索所有ListItem

到目前为止,我的思考过程一直是将所有DropDownList控件提取到一个新列表中,并进行迭代以拉出每个ListItem但是,每个DropDownList控件都有0个项目

ControlCollection cList = pnlContent.Controls;

List<DropDownList> ddlList = new List<DropDownList>();
foreach (Control c in cList)
{
    if (c.GetType() == new DropDownList().GetType())
    {
        ddlList.Add((DropDownList)c);
    }
}

ListItemCollection itemCollection = new ListItemCollection();
foreach (DropDownList ddl in ddlList)
{
    foreach(ListItem li in ddl.Items)
    {
        itemCollection.Add(li);
    }
}

我确信这是错误的(而且效率很低)。 任何帮助,将不胜感激。

这样可以:

public IEnumerable<ListItem> GetListItems(ControlCollection controls)
{
    return controls.OfType<DropDownList>().SelectMany(c => c.Items.OfType<ListItem>());
}

我目前没有可以测试此功能的安装程序,但从思路上讲,我将使用Linq进行此操作。

这是一个您应该可以使用的示例;

var type = new DropDownList().GetType();

var listOfControl = from c in pnlContent.Controls
                    where c.GetType() == type
                    select ((DropDownList)c).Items;

尝试这个:

 var ddlList = cList.OfType<DropDownList>();


 ListItemCollection itemCollection = new ListItemCollection();
 // option 1
 var temp = ddlList.Select(ddl => ddl.Items.Cast<ListItem>()).SelectMany(li => li).ToArray();
 itemCollection.AddRange(temp);
 // or option 2
 var temp = ddlList.Select(ddl => ddl.Items.Cast<ListItem>()).SelectMany(li => li);
 foreach (var listItem in temp)
 {
     itemCollection.Add(listItem);
 }
        comboBox1.Items.Add(button1);
        comboBox1.Items.Add(button2);
        comboBox1.Items.Add(dateTimePicker1);
        comboBox1.Items.Add(checkBox1);

        comboBox2.Items.Add(button3);
        comboBox2.Items.Add(button4);
        comboBox2.Items.Add(dateTimePicker2);
        comboBox2.Items.Add(checkBox2);

        comboBox3.Items.Add(button5);
        comboBox3.Items.Add(dateTimePicker3);
        comboBox3.Items.Add(checkBox3);
        comboBox3.Items.Add(checkBox4);

        List<ComboBox> ddlList = new List<ComboBox>();
        foreach (Control c in panel1.Controls)
        {
            if (c is ComboBox)
            {
                ddlList.Add((ComboBox)c);
            }
        }

        List<Control> itemCollection = new List<Control>();

        foreach (ComboBox ddl in ddlList)
        {
            foreach (var li in ddl.Items)
            {
                itemCollection.Add((Control)li);
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM