bind dropdownlist using XML

2019-08-29 13:05发布

问题:

i am new to ASP.NET,

i am making Country, state dropdownlist.

for eg: For particular country, i will read states of that country from XML file.

here is my code snippet in XMLFile.xml

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

  <country>India</country>
  <state>
    <text>Maharashtra</text>
    <text>Kashmir</text>
    <text>Goa</text>   
  </state>

  <country>Sri Lanka</country>
  <state>
    <text>Kanady</text>
    <text>Colombo</text>
    <text>Galle</text> 
  </state>

  <country>Australia</country>
  <state>
    <text>Sydney</text>
    <text>Perth</text>
    <text>Melbourne</text>
  </state>

  <country>South Africa</country>
  <state>
    <text>Capetown</text>
    <text>Johanusburg</text>
    <text>Durban</text>
  </state>
</countrys>

and code in Country.aspx.cs

   public partial class Country : System.Web.UI.Page
   {
       protected void Page_Load(object sender, EventArgs e)
       {

            if (!IsPostBack)
            {
                LoadDropdown();
            }
     }

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

            DropDownListCountry.DataTextField = "country";

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

    protected void DropDownListCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
            string  st = (DropDownListCountry.SelectedIndex).ToString();

             XDocument main = XDocument.Load(@"XMLFile.xml");

        var query = from user in main.Descendants("country_text")
                where st == user.Element("state").Value
                select user;

        DropDownListState.DataSource = query;
        DropDownListState.DataBind();     
    }
}

ERROR : DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'country'.

回答1:

Bind it to country_text

DropDownListCountry.DataTextField = "country_text";

You have three tables in your dataset. Country,State and Text. The field in dataset holding country value is country_text and thats what you should bind to