有没有更好的方法来填充多个下拉列表?

时间:2015-11-09 16:05:58

标签: c# asp.net

我需要填充几个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>

1 个答案:

答案 0 :(得分:5)

把它们放在一个数组中:

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个相同的下拉菜单?是否有可能为他们使用某种中继器?