Saturday, 26 October 2013

Asp.net dropdown list populated with data from .xml file

In asp.net we have <asp:DropDownList> control , to populate this control with data from .xml file , you need to do straight and simple three steps.

Step#1 : Create xml file in your project , lets say we have data of countries i.e

<?xml version="1.0" encoding="utf-8" ?>
<Countries>
  <Country>
    <Id>1</Id>
    <Name>India</Name>
  </Country>
  <Country>
    <Id>2</Id>
    <Name>USA</Name>
  </Country>
    <Country>
      <Id>3</Id>
      <Name>Japan</Name>
    </Country>
    <Country>
      <Id>4</Id>
      <Name>Australia</Name>
    </Country>
    <Country>
      <Id>5</Id>
      <Name>England</Name>
    </Country>
    <Country>
      <Id>6</Id>
      <Name>UAE</Name>
    </Country>
    <Country>
      <Id>7</Id>
      <Name>China</Name>
    </Country>
  </Countries>

Copy paste this data as it is in your Countries.xml file.

Step#2 : Now you must have DropDownList control on your page .Put following code inside your .aspx page. 


        <asp:DropDownList ID="ddlCountries" runat="server" AutoPostBack="True" Width="183px">  
        </asp:DropDownList>

Step#3 : Now go to your code behind file and define following function there :

  public void BindDropDownListFromXml()
        {
            DataSet ds = new DataSet();
            try
            {
                //Reading the data from the XML file
                ds.ReadXml(MapPath("~/Countries.xml"));
                DataView dv = ds.Tables[0].DefaultView;
                //Sort the DataView by "Name"
                dv.Sort = "Name";
                //Setting DataText field and DataValue field of DropDownList
                ddlCountries.DataTextField = "Name";
                ddlCountries.DataValueField = "ID";
                //Binding the DropDownList with the  DataView
                ddlCountries.DataSource = dv;
                ddlCountries.DataBind();
                ddlCountries.Items.Insert(0, new ListItem("-- Select --", "0"));
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }
        }

And after this , call this function inside your Page_Load function like this :

  protected void Page_Load(object sender, EventArgs e)
        {
            //this will run on page load
            if (!Page.IsPostBack)
            {
                BindDropDownListFromXml();
            }  
        }

And that's it :)

No comments:

Post a Comment