有没有更好的方法来填充多个下拉列表
本文关键字:下拉列表 填充 更好 方法 有没有 | 更新日期: 2023-09-27 18:21:09
我需要填充几个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个相同的下拉菜单呢?有可能为他们使用某种中继器吗?