Saturday, 3 August 2013

Populate Dropdown From XML using C#

    protected void BindDataToDropdownlist()
    {
        XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("Sample.xml"));
        DataSet ds = new DataSet();
        ds.ReadXml(xmlreader);
        xmlreader.Close();
        if (ds.Tables.Count != 0)
        {
            //Bind Data to dropdownlist
            ddlCity.DataSource = ds;
            ddlCity.DataTextField = "Name";
            ddlCity.DataValueField = "Id";
            ddlCity.DataBind();
        }
    }


XML
====
<?xml version="1.0" encoding="utf-8" ?>
<cities>
  <city>
    <Name>Kolkata</Name>
    <Id>1</Id>
  </city>
<city>
    <Name>Delhi</Name>
    <Id>2</Id>
  </city>
<city>
    <Name>Mumbai</Name>
    <Id>3</Id>
  </city>
</cities>