Thursday, 19 August 2010

Binding a dropdown list to an XML file of countries

using System.Xml; 

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
      Bind_ddlCountries();
}

private void Bind_ddlCountries()
{
   XmlDocument doc = new XmlDocument();
   doc.Load(Server.MapPath("countries.xml"));

   foreach (XmlNode node in doc.SelectNodes("//country"))
   {
      ddlCountries.Items.Add(new ListItem(node.InnerText, node.InnerText));
   }
} 
and the source xml country list should look like this:
<countries>
<country>Algeria</country>
<country>Brazil</country>
<country>Colombia</country>
</countries>
You can get the full list of countries I most recently used here.

No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!