Tuesday, October 23, 2012

Bind asp.net dropdownlist to xml file


Fig: Binding asp.net dropdownlist control to an xml file
Today I am discussing the simple way to bind an asp.net dropdownlist control to an xml file. Besides binding the dropdownlist controls to an xml file, we will also sort the items in the ascending order.
Let us define the xml file first. This consists of Country object with properties ID and Name.

  1. xml version="1.0" encoding="utf-8" ?>  
  2. <Countries>  
  3.   <Country>  
  4.     <ID>1</ID>  
  5.     <Name>Nepal</Name>  
  6.   </Country>  
  7.   <Country>  
  8.     <ID>2</ID>  
  9.     <Name>India</Name>  
  10.     <Country>  
  11.       <ID>3</ID>  
  12.       <Name>China</Name>  
  13.     </Country>  
  14.     <Country>  
  15.       <ID>4</ID>  
  16.       <Name>Bhutan</Name>  
  17.     </Country>  
  18.     <Country>  
  19.       <ID>5</ID>  
  20.       <Name>USA</Name>  
  21.     </Country>  
  22.   </Country>  
  23. </Countries>  
We place this xml file in the Resources folder of the root of our solution. Now let us define the markup for the asp.net dropdownlist control.

  1. Select from the list of countries:</b> <asp:DropDownList ID="ddlCountry" runat="server"  
  2.             Width="160px"></asp:DropDownList>  
Now in the load event of the page, we read the items from the xml file into a dataset. We will get the DataView for the default table in the dataset, and sort it. The table will consists of as many rows as there are country objects in the xml file. Each row has two columns: ID and Name. Now we can bind this dataview to the dropdownlist control, as in the code (in C#) below.

  1. //page load event handler  
  2.     protected void Page_Load(object sender, EventArgs e)  
  3.     {  
  4.         if (!IsPostBack)  
  5.         {  
  6.             //call to the function to populate dropdownlist from xml  
  7.             PopulateDDLFromXMLFile();  
  8.         }  
  9.     }  
  10.   
  11.     //populates the dropdownlist from xml file  
  12.     public void PopulateDDLFromXMLFile()  
  13.     {  
  14.         DataSet ds = new DataSet();  
  15.         ds.ReadXml(MapPath("~/Resources/XMLFile.xml"));  
  16.   
  17.         //get the dataview of table "Country", which is default table name  
  18.         DataView dv = ds.Tables["Country"].DefaultView;  
  19.         //or we can use:  
  20.         //DataView dv = ds.Tables[0].DefaultView;  
  21.   
  22.         //Now sort the DataView vy column name "Name"  
  23.         dv.Sort = "Name";  
  24.   
  25.         //now define datatext field and datavalue field of dropdownlist  
  26.         ddlCountry.DataTextField = "Name";  
  27.         ddlCountry.DataValueField = "ID";  
  28.   
  29.         //now bind the dropdownlist to the dataview  
  30.         ddlCountry.DataSource = dv;  
  31.         ddlCountry.DataBind();  
  32.     }  
That simple! Happy Programming!