Get selected option for all DropDown-lists [duplicate]

南楼画角 提交于 2019-12-10 12:57:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!