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" "">  
 <html xmlns="">  
 <head runat="server">  
   <form id="form1" runat="server">  
     <asp:DropDownList ID="DropDownList1" runat="server">  

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");  
       DropDownList1.DataTextField = "CountryName";  
       DropDownList1.DataValueField = "CountryId";  
       DropDownList1.DataSource = DS;  
       ListItem li = new ListItem("Select","-1");  

 <?xml version="1.0" encoding="utf-8" ?>   

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