Sunday 22 December 2013

Bind Dropdownlist with XML File

Here I am explaining how to bind an XML fine to ASP.Net DropDownList control.
XML file
Below is my Cities.xml which I contains the list of some Indian cities.


<?xmlversion="1.0"encoding="utf-8" ?>
<cities>
 <city>
    <id>1</id>
    <name>Mumbai</name>
 </city>
 <city>
    <id>2</id>
    <name>Delhi</name>
 </city>
 <city>
    <id>3</id>
    <name>Chennai</name>
 </city>
 <city>
    <id>4</id>
    <name>Kolkatta</name>
 </city>
</cities>

The name of the City will be assigned to the Text part and the id will be assigned to the Value
 part of the ASP.Net DropDownList Control.
Namespace
You will need to import the following namespace.
C#

using System.Data;

Reading the XML file and Binding the DropDownList
Below is the method that reads the XML file into a Dataset object and then binds the same to the ASP.Net DropDownList Control
C#


private void BindXml()
{
    string filePath = Server.MapPath("~/Cities.xml");
    using (DataSet ds = new DataSet())
    {
        ds.ReadXml(filePath);
        ddlCities.DataSource = ds;
        ddlCities.DataTextField = "name";
        ddlCities.DataValueField = "id";
        ddlCities.DataBind();
    }
}
I am calling the above method in the Page Load event of the Page in the following way
C#


protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindXml();
    }
}

No comments:

Post a Comment