How to populate a drop down list from an XML file in .NET

February 26, 2009 - 5:48 pm 1 Comment

I know this is not rocket science but it’s actually something I’d never had to do until recently. Normally I populate my drop down lists (and repeaters, etc etc) using data from databases, not XML.

However, fear not. Using XML as a datasource in .NET is super easy. Here is one way to do it:

?View Code CSHARP
1
2
3
4
5
6
7
8
XmlDataSource source = new XmlDataSource();
source.DataFile = Server.MapPath("Values.xml");
source.XPath = "ParentElement/ValueList/ValueItem";
 
myDropDownList.DataSource = source;
myDropDownList.DataTextField = "Text";
myDropDownList.DataValueField = "Value";
myDropDownList.DataBind();

And your xml file, Values.xml, may look something like:

<?xml version="1.0" encoding="utf-8"  standalone="yes" ?>
<ParentElement>
  <ValueList>
    <ValueItem Text="Item 1" Value="1" />
    <ValueItem Text="Item 2" Value="2" />
  </ValueList>
</ParentElement>

Happy coding!

  • Share/Bookmark

One Response to “How to populate a drop down list from an XML file in .NET”

  1. Chris Says:

    Wow, that’s really useful! I thought it would’ve taken a whole lot more code but apparently not. Thanks! :)

Leave a Reply