Bind Dropdown through XML file using asp.net (#)


Here I m going to bind my country dropdown list through xml file. Please have a look into that it’s really very simple and amazing. Here it goes:

Step 1: Create a Country.xml file as below given:

xml version="1.0" encoding="utf-8" ?>
<Countries>
 
<Country ID="IN001" Name="India">Country>
<Country ID="CH001" Name="China">Country>
<Country ID="UA001" Name="UAE">Country>
<Country ID="UK001" Name="London">Country>
<Country ID="AM001" Name="America">Country>
 
Countries>

.aspx file

Create a dropdown in your .aspx page

<asp:DropDownList ID="ddlCountry" runat="server">asp:DropDownList>

.aspx.cs page

Create a function ‘BindCountry()’ as below:

    protected void BindCountry()
    {
        //DataSet decliaration
        DataSet dsCountry = new DataSet();
        //Read xml and assign to DataSet
        dsCountry.ReadXml(Server.MapPath("~/Country.xml"));
        //Bind through DataView (i.e. sort purpose)
        DataView dv = (DataView)dsCountry.Tables[0].DefaultView;
        ddlCountry.DataSource = dv;
        //Sort by Country Name
        dv.Sort = "Name ASC";
        ddlCountry.DataTextField = "Name";
        ddlCountry.DataValueField = "ID";
        ddlCountry.DataBind();
    }

Call the function on page load:

if (!IsPostBack)
        {
           //Bind Drop Down List
            BindCountry();
        }

Comments