Populating ASP.NET DropDownList Control using XML File

Step 1: Creating the Required XML File named 'Countries.xml'.

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <Countries>  
  3.     <Country>  
  4.         <CountryID>1</CountryID>  
  5.         <CountryName>India</CountryName>  
  6.     </Country>  
  7.     <Country>  
  8.         <CountryID>2</CountryID>  
  9.         <CountryName>USA</CountryName>  
  10.     </Country>  
  11.     <Country>  
  12.         <CountryID>3</CountryID>  
  13.         <CountryName>China</CountryName>  
  14.     </Country>  
  15.     <Country>  
  16.         <CountryID>4</CountryID>  
  17.         <CountryName>Australia</CountryName>  
  18.     </Country>  
  19.     <Country>  
  20.         <CountryID>5</CountryID>  
  21.         <CountryName>United Kingdom</CountryName>  
  22.     </Country>  
  23.     <Country>  
  24.         <CountryID>6</CountryID>  
  25.         <CountryName>Brazil</CountryName>  
  26.     </Country>  
  27. </Countries>    
Step 2: Drag and Drop a Dropdownlist Control from ASP.NET Controls Toolbox and Press F7 Key to Add the Below code to the Code Behind File.

  1. using System;    
  2. using System.Data;    
  3. using System.Web.UI.WebControls;    
  4. namespace DDLPopulateWithXML    
  5. {    
  6.     public partial class WebForm1 : System.Web.UI.Page    
  7.     {    
  8.         protected void Page_Load(object sender, EventArgs e)    
  9.         {    
  10.             if (!IsPostBack) //Used to Check that Whether the page loads first time or Second Time    
  11.             {    
  12.                 DataSet ds = new DataSet(); //Created a Dataset to Store data    
  13.                 ds.ReadXml(Server.MapPath("Countries.xml")); // Using ReadXml Method of the Dataset Class and Server.MapPath is used to  
  14. Get the Correct path of the XML File    
  15.                 DropDownList1.DataSource = ds; //Setting the Datasource of DDL to Dataset    
  16.                 DropDownList1.DataTextField = "CountryName"//This is the name of the tag of XML file through which we want to Show the Values    
  17.                 DropDownList1.DataValueField = "CountryID"//This is the Primary key on which the Data is fetched    
  18.                 DropDownList1.DataBind(); //Data is Binded with the dropdownlist    
  19.                 ListItem LI = new ListItem("---Select---""-1"); //Used to Show Some Custom Text in the list of DDL    
  20.                 DropDownList1.Items.Insert(0,LI); //Used to Insert the Above Value at the 0 Index Location of the DDL, so that It appears  
  21. on Top    
  22.             }    
  23.         }    
  24.     }    
  25. }