c# – 获取所有DropDown列表的选定选项

参见英文答案 > How can I get the selected item of a dropdownlist,the first time my page loads?4个
我试图在我的页面获取所有下拉列表,并在每个下拉列表中选择所选项目文本/值.但我似乎错过了一些东西.
foreach (DropDownList dr in this.Page.Form.Controls.OfType<DropDownList>()) {
    foreach (ListItem li in dr.Items) {
            if (li.Selected) {
            //put the selected items value/text into something.
        }
    }
}

有没有想过这样做?

编辑:使其更清晰.我有一个随机数量的DropDownLists,我可以选择1个选项pr Dropdownlist.当我按下按钮时,我需要从每个DropDownLists中选择的内容获取信息. (DropDownLists上没有ID,有一个随机数).

解决方法

protected void Button1_Click(object sender,EventArgs e)
    {
        List<DropDownList> lst = new List<DropDownList>();
        GetDropDownControls(GetlistofControlCollection(this.Form.Controls),ref lst);

        foreach (DropDownList item in lst)
        {
            var selectedValue = item.SelectedValue;
            //to do something with value
        }

    }

        void GetDropDownControls(List<Control> controls,ref List<DropDownList> lst)
    {
        foreach (Control item in controls)
        {
            if (item.Controls.Count == 0 && item is DropDownList)
                lst.Add((DropDownList)item);
            else
                if (item.Controls.Count > 0)
                    GetDropDownControls(GetlistofControlCollection(item.Controls),ref lst);
        }
    }

    List<Control> GetlistofControlCollection(ControlCollection controls)
    {
        List<Control> result = new List<Control>();
        foreach (Control item in controls)
        {
            result.Add(item);
        }
        return result;
    }

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么