Subscribe to Blog.Parse(typeof(PsychoCoder), Richard McCutchen);        RSS Feed

Use LINQ To XML to populate DropDownList

Icon 3 Comments
Recently I had someone approach me with a question; They needed to load a DropDownList with all the states (abbreviations only) but didn't want to use SQL as an option for resource sake. The solution I came up with was to introduce them to LINQ To XML as an efficient way of accomplishing this. Of course (like many) they had never done anything with XML let alone LINQ, so I helped them learn it, kind of a crash course.

First thing I needed was an XML file with all the states in it (Shockingly I already had one, weird huh) and I will offer that with this post (here you go)

<?xml version="1.0" encoding="utf-8" ?>
	<state name="ALABAMA" abbreviation="AL" />
	<state name="ALASKA" abbreviation="AK" />
	<state name="AMERICAN SAMOA" abbreviation="AS" />
	<state name="ARIZONA" abbreviation="AZ" />
	<state name="ARKANSAS" abbreviation="AR" />
	<state name="CALIFORNIA" abbreviation="CA" />
	<state name="COLORADO" abbreviation="CO" />
	<state name="CONNECTICUT" abbreviation="CT" />
	<state name="DELAWARE" abbreviation="DE" />
	<state name="DISTRICT OF COLUMBIA" abbreviation="DC" />
	<state name="FEDERATED STATES OF MICRONESIA" abbreviation="FM" />
	<state name="FLORIDA" abbreviation="FL" />
	<state name="GEORGIA" abbreviation="GA" />
	<state name="GUAM" abbreviation="GU" />
	<state name="HAWAII" abbreviation="HI" />
	<state name="IDAHO" abbreviation="ID" />
	<state name="ILLINOIS" abbreviation="IL" />
	<state name="INDIANA" abbreviation="IN" />
	<state name="IOWA" abbreviation="IA" />
	<state name="KANSAS" abbreviation="KS" />
	<state name="KENTUCKY" abbreviation="KY" />
	<state name="LOUISIANA" abbreviation="LA" />
	<state name="MAINE" abbreviation="ME" />
	<state name="MARSHALL ISLANDS" abbreviation="MH" />
	<state name="MARYLAND" abbreviation="MD" />
	<state name="MASSACHUSETTS" abbreviation="MA" />
	<state name="MICHIGAN" abbreviation="MI" />
	<state name="MINNESOTA" abbreviation="MN" />
	<state name="MISSISSIPPI" abbreviation="MS" />
	<state name="MISSOURI" abbreviation="MO" />
	<state name="MONTANA" abbreviation="MT" />
	<state name="NEBRASKA" abbreviation="NE" />
	<state name="NEVADA" abbreviation="NV" />
	<state name="NEW HAMPSHIRE" abbreviation="NH" />
	<state name="NEW JERSEY" abbreviation="NJ" />
	<state name="NEW MEXICO" abbreviation="NM" />
	<state name="NEW YORK" abbreviation="NY" />
	<state name="NORTH CAROLINA" abbreviation="NC" />
	<state name="NORTH DAKOTA" abbreviation="ND" />
	<state name="NORTHERN MARIANA ISLANDS" abbreviation="MP" />
	<state name="OHIO" abbreviation="OH" />
	<state name="OKLAHOMA" abbreviation="OK" />
	<state name="OREGON" abbreviation="OR" />
	<state name="PALAU" abbreviation="PW" />
	<state name="PENNSYLVANIA" abbreviation="PA" />
	<state name="PUERTO RICO" abbreviation="PR" />
	<state name="RHODE ISLAND" abbreviation="RI" />
	<state name="SOUTH CAROLINA" abbreviation="SC" />
	<state name="SOUTH DAKOTA" abbreviation="SD" />
	<state name="TENNESSEE" abbreviation="TN" />
	<state name="TEXAS" abbreviation="TX" />
	<state name="UTAH" abbreviation="UT" />
	<state name="VERMONT" abbreviation="VT" />
	<state name="VIRGIN ISLANDS" abbreviation="VI" />
	<state name="VIRGINIA" abbreviation="VA" />
	<state name="WASHINGTON" abbreviation="WA" />
	<state name="WEST VIRGINIA" abbreviation="WV" />
	<state name="WISCONSIN" abbreviation="WI" />
	<state name="WYOMING" abbreviation="WY" />

Now to the fun stuff. The easiest way (for me) to do this is by using the XDocument Class, and use it's Load Method to load my XML. From there I'd use LINQ to query the XML file. Once I have all the abbreviations I then loop through the results adding them to a Generic List (We'll be using that list to populate our DropDownList).

This is how that looks

/// <summary>
/// method utilizing Linq To Xml for retrieving the state abbreviations
/// from an XML file
/// </summary>
/// <returns></returns>
public List<string> getStatesList()
	//Create an XDocument instance (
	XDocument doc = Xdocument.Load(_xmlFile);

	//Generic list to hold the state abbreviations
	List<string> stateList = new List<string>();

		//now use LINQ to Xml to get just the state abbreviations
		var states = from s in doc.Elements("states").Elements("state")
					 select (string)s.Attribute("abbreviation");

	//now loop through each and add to our Generic list
	foreach (var state in states)

	//get rid of the XDocument instance
	doc = null;

	//return the state abbreviations
	return stateList;

Now that I have the data in a list (The above function is part of it's own class named XmlWork so that's what the next portion of code will be referencing) I create an instance of my XmlWork class in the Page's Load event. I then use LINQ to traverse the Generic List and populate the DropDownList (I use LINQ in order to sort the list to make sure it's in the proper order).

protected void Page_Load(object sender, EventArgs e)
	XmlWork xml = new XmlWork();

	xml.XmlFile = Server.MapPath(@"~/XMLFiles/states.xml");
	List<string> states = xml.getStatesList(); 

   //use LINQ to make sure our states are in alphabetical order
	var statesList = from s in states
					 orderby s ascending
					 select s;

	//load the states list
	foreach (string str in statesList)

   //Add a [Select One] option as the first option
	State.Items.Insert(0, "[Select One]");
	State.SelectedIndex = 0;

Well this was an interesting thing to write about, along with offering some code to those who may have the need to accomplish something like this in their applications. Thanks for reading :)

3 Comments On This Entry

Page 1 of 1


19 June 2009 - 06:11 AM
I find this very ironic. I was just yesterday looking at working with XML in C#. Then behold the wonderful Psycho. Thanks man this is great.


19 June 2009 - 07:35 AM
No problem Smurphy glad I could help. Remember, this example is for 3.0 and above


19 June 2009 - 09:45 AM
I liked the article. :^: I'm looking at starting a new editor for my xml, but it uses a schema. Any suggestions on a good starting point?
Page 1 of 1

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

July 2020

5678910 11

Recent Entries

Search My Blog

1 user(s) viewing

1 Guests
0 member(s)
0 anonymous member(s)