簡體   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