Today, I had to bind a list of countries to a drop down list in ASP.NET 2.0. I wanted
to use an XML file to store the countries. There are more than 200 so there was not
way I was going to hard code them in the HTML.
I have done this many times before, but never from an XML file. Normally I store the
countries in a database, because other database tables would reference it. Today, I just wanted a list of countries with no relation to any data at all.
My plan was clear and simple. Find an XML file of countries on the internet and bind
them to a drop down list. How hard could that be? After 15 minutes of searching Google and Live.com for
the XML country file I gave up. It wasn’t out there.
Luckily, I have dozens of country tables in various databases I’ve built during the
last couple of years, so I generated my own XML list by exporting from SQL server
to a CSV file and then created a method in C# that generated the XML file from it.
For anybody else in need for an XML country list, look no further. I’ll share mine
with you.
If you want to bind it to a drop down list, here’s the code for that. First add the
drop down list to your page:
<asp:DropDownList
runat="Server" ID="ddlCountry" />
Then use this C# code to bind the countries to the drop down list:
using System.Xml;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindCountry();
}
private void BindCountry()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("countries.xml"));
foreach (XmlNode
node in doc.SelectNodes("//country"))
{
ddlCountry.Items.Add(new ListItem(node.InnerText, node.Attributes["code"].InnerText));
}
}
Remember to add the countries.xml in the root of your website.
Download countries.xml
(12,48 KB)
* $4.95/month BlogEngine.net Hosting – Click Here!