无法将数据绑定到DropDownList

时间:2012-06-04 18:01:08

标签: c# asp.net .net xml data-binding

我将XML值绑定到DropDownList。以下是我的代码:

protected void LoadDropdown()
{
     DataSet ds = new DataSet();
     ds.ReadXml (Server.MapPath(@"XMLFile1.xml"));

     DropDownList1.DataTextField = "country_Id";          
     DropDownList1.DataSource = ds;
     DropDownList1.DataBind();
     DropDownList1.Items.Insert(0,new ListItem(" Select ","0"));
}     

我想在DropDownList中获取国家/地区名称,但我得到的ID值为0,1,2,3。我做错了什么?

3 个答案:

答案 0 :(得分:1)

尝试为DataTextField指定其他内容:

DropDownList1.DataTextField = "country_Name"; //This value depends on what your XML structure is.
DropDownList1.DataValueField = "country_Id";

答案 1 :(得分:0)

如果xml看起来像这样

<?xml version="1.0" encoding="utf-8" ?>

<Items>
<Item ddlValue="1" ddlText="YourlistItem1" />
<Item ddlValue="2" ddlText="YourlistItem2" />
<Item ddlValue="3" ddlText="YourlistItem3" />
</Items>

您的下拉列表的代码应该是

protected void Page_Load(object sender, EventArgs e)
{
    DataSet ddlDataSource = new DataSet(); 
    ddlDataSource.ReadXml(MapPath("XmlFile.xml"));
    DropDownList1.DataSource = ddlDataSource;
    DropDownList1.DataBind();
} 

希望这会有所帮助。

答案 2 :(得分:0)

我找到了解决问题的方法。

protected void LoadDropdown()
    {
        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath(@"XMLFile1.xml"));
        DropDownList1.DataTextField = "name";
        DropDownList1.DataSource = ds;
        DropDownList1.DataBind();
        DropDownList1.Items.Insert(0, new ListItem(" Select ", "0"));
    }