问题
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.
}
}
}
Any idea to do this?
Edit: 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).
回答1:
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;
}
来源:https://stackoverflow.com/questions/34328245/get-selected-option-for-all-dropdown-lists