| The easiest way to populate drop down list with XML in C# |
|
Populating the drop down list is fairly straigth forward and you can accomplish this task in a few minutes. I have included a sample project which you can download and try it on your computer. Basically there are 3 steps to populate the drop drop down list: 1. Create a new dataset. XML FILE: </student> <student> <StudentID>2</StudentID> <StudentName>Bob</StudentName> </student> <student> <StudentID>3</StudentID> <StudentName>Ben</StudentName> </student> <student> <StudentID>4</StudentID> <StudentName>Julie</StudentName> </student> <student> <StudentID>5</StudentID> <StudentName>Oliver</StudentName> </student> </Students>
ASPX FILE:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="LoadDropDownListFromXML._Default" %>
<!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>Easist way to load drop down list from XML file</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList ID="DropDownList1" runat="server"> </asp:DropDownList> </div> </form> </body> </html>
CODE BEHIND FILE: using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq;
namespace LoadDropDownListFromXML { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { LoadXML(); }
public void LoadXML() { string myXMLfile = Server.MapPath("~/StudentXML.xml"); DataSet dsStudent = new DataSet(); try { dsStudent.ReadXml(myXMLfile); DropDownList1.DataSource = dsStudent; DropDownList1.DataValueField = "StudentID"; DropDownList1.DataTextField = "StudentName"; DropDownList1.DataBind(); } catch (Exception ex) { Response.Write(ex.ToString()); } } } } Download the sample project
Comments (3)
!joomlacomment 4.0 Copyright (C) 2009 Compojoom.com . All rights reserved."
|