gpt4 book ai didi

c# - 获取所有下拉列表的选定选项

转载 作者:行者123 更新时间:2023-12-02 09:46:43 24 4
gpt4 key购买 nike

我试图获取页面上的所有下拉列表,以及每个下拉列表中所选项目的文本/值。但我似乎错过了一些东西。

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.
}
}
}

有什么想法吗?

编辑:使其更清楚。我有随机数量的 DropDownList,我可以在 Dropdownlist 中选择 1 个选项。当我按下按钮时,我需要从每个 DropDownList 中选择的内容中获取信息。 (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;
}

关于c# - 获取所有下拉列表的选定选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34328245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com