我需要填充多个 DropDownList,并且我搜索了更好的方法来执行此操作,因为我有 8 个 DropDownList 需要填充。在我看来,这不是最好的方法,你有 8 次相同的代码......可以使用循环吗?
public partial class MainPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DropDownList();
}
public void DropDownList()
{
string filePath = Server.MapPath("~/Datas.xml");
using (DataSet ds = new DataSet())
{
ds.ReadXml(filePath);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
DropDownList2.DataSource = ds;
DropDownList2.DataTextField = "name";
DropDownList2.DataValueField = "id";
DropDownList2.DataBind();
//Then DropDownList3, 4, 5, 6....8
}
}
}
这是我的用户的 XML:
<?xml version="1.0" encoding="utf-8" ?>
<users>
<user>
<id>1</id>
<name>User1</name>
</user>
<user>
<id>2</id>
<name>User2</name>
</user>
<user>
<id>3</id>
<name>User3</name>
</user>
<user>
<id>4</id>
<name>User4</name>
</user>
</users>
最佳答案
只需将它们放在一个数组中:
DropDownList[] ddls = new DropDownList[]{
DropDownList1, DropDownList2,
DropDownList3, DropDownList4,
...
};
然后遍历它:
foreach (DropDownList ddl in ddls)
{
ddl.DataSource = ds;
ddl.DataTextField = "name";
ddl.DataValueField = "id";
ddl.DataBind();
}
附带说明 - 您怎么会在 UI 端得到 8 个相同的下拉菜单?是否可以为他们使用某种中继器?
关于c# - 有没有更好的方法来填充多个下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33613250/