[thelist] populating a drop down list from an XML doc

Jason Hepi contact at hepi.fsnet.co.uk
Tue Mar 11 08:43:48 CST 2003


Using the System.Xml namespace and the Items collection Add method to
populate name value pairs programmatically to the DropDownList control is
one way of doing it :

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;

..
..

private void Page_Load(object sender, System.EventArgs e) {
 string Path = Request.PhysicalApplicationPath;
 DataSet datadoc = new DataSet();
 datadoc.ReadXml(Path + "source.xml");

 XmlDataDocument xmlDataDoc = new XmlDataDocument(datadoc);
 string strXPathQuery = "/root/department";
 foreach (XmlNode nodeDetail in xmlDataDoc.SelectNodes(strXPathQuery))
 {
  string itemText = nodeDetail.ChildNodes[1].InnerText.ToString();
  string itemValue = nodeDetail.ChildNodes[0].InnerText.ToString();
  ddlDepartments.Items.Add(new ListItem(itemValue, itemText));
 }
}


I've added a <root> element to your xml file to make it a more valid
document (and easier to reference XPath queries) e.g.

<?xml version="1.0" encoding="utf-8" ?>
<root>
<department>
	<departmentName>IT</departmentName>
	<pathToIntranet>/IT/default.aspx</pathToIntranet>
</department>
<department>
	<departmentName>web</departmentName>
	<pathToIntranet>/web/ default.aspx </pathToIntranet>
</department>
</root>


HTH's

Jason





More information about the thelist mailing list