获取所有下拉列表的选定选项 [英] Get selected option for all DropDown-lists
本文介绍了获取所有下拉列表的选定选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在页面上获取所有下拉列表,并在每个下拉列表中选择项目的文本/值.但是我似乎丢失了一些东西.
I am trying to get all dropdownlists on my page, and in each of them the selected item text/value. But I am seem to be missing something.
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,有一个随机数.)
To make it more clear. I have a random amount of DropDownLists, where i can select 1 option pr Dropdownlist. When I push a button, i need to get the information from what i have selected in each DropDownLists. (There is no ID on the DropDownLists, that there is a random number).
推荐答案
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;
}
这篇关于获取所有下拉列表的选定选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文