Sunday, June 1, 2014

Data binding DropDownList to an XML file

To add the XML file:-
Right click on the project-->Add -->New Item-->Select visual C# tab--> Select XML.
ReadXml() method of the Dataset object can be used to read from the XML file into a DataSet.
Server.MapPath() method return the physical path for a given virtual path.

Example to add list items that are present in XML file.
WebForm1.aspx :-
 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="_18_Dropdown_with_XML.WebForm1" %>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
 <html xmlns="http://www.w3.org/1999/xhtml">  
 <head runat="server">  
   <title></title>  
 </head>  
 <body>  
   <form id="form1" runat="server">  
   <div>  
     <asp:DropDownList ID="DropDownList1" runat="server">  
     </asp:DropDownList>  
   </div>  
   </form>  
 </body>  
 </html>  

WebForm1.aspx.cs :-
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 using System.Data;  
 namespace _18_Dropdown_with_XML  
 {  
   public partial class WebForm1 : System.Web.UI.Page  
   {  
     protected void Page_Load(object sender, EventArgs e)  
     {  
       DataSet DS = new DataSet();  
       string strPhysicalPath = Server.MapPath("Countries.xml");  
       DS.ReadXml(strPhysicalPath);  
       DropDownList1.DataTextField = "CountryName";  
       DropDownList1.DataValueField = "CountryId";  
       DropDownList1.DataSource = DS;  
       DropDownList1.DataBind();  
       ListItem li = new ListItem("Select","-1");  
       //DropDownList1.Items.Add(li);  
       DropDownList1.Items.Insert(0,li);  
     }  
   }  
 }  

Countries.xml:-
 <?xml version="1.0" encoding="utf-8" ?>   
 <Countries>  
   <Country>  
    <CountryId>101</CountryId>  
    <CountryName>London</CountryName>  
   </Country>  
  <Country>  
   <CountryId>102</CountryId>  
   <CountryName>Canada</CountryName>  
  </Country>  
  <Country>  
   <CountryId>103</CountryId>  
   <CountryName>Australiya</CountryName>  
  </Country>  
  <Country>  
   <CountryId>104</CountryId>  
   <CountryName>India</CountryName>  
  </Country>  
 </Countries>  


To insert a ListItem at a specific location use the Insert() method.Here we have to specify which value you want to show in the dropdown list and which value you want to halt as the value of the list item object.

No comments:

Post a Comment