Bind countries from CultureInfo class in C#

May 27, 2007

Some people have asked me how BlogEngine.NET displays a dropdown list of countries when no source XML file is present. The simple answer is that you don’t need any external list to bind to from C#, you can instead use the CultureInfo class.

Consider that you have the following dropdown list declared in an ASP.NET page:

<asp:DropDownList runat="server" ID="ddlCountry" />

Then from code-behind, call this method which binds the countries alphabetically to the dropdown:

public void BindCountries()
{
  System.Collections.Specialized.StringDictionary dic = new System.Collections.Specialized.StringDictionary();
  System.Collections.Generic.List<string> col = new System.Collections.Generic.List<string>();

  foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures))
  {
    RegionInfo ri = new RegionInfo(ci.LCID);
    if (!dic.ContainsKey(ri.EnglishName))
      dic.Add(ri.EnglishName, ri.TwoLetterISORegionName.ToLowerInvariant());

    if (!col.Contains(ri.EnglishName))
      col.Add(ri.EnglishName);
  }

  col.Sort();

  ddlCountry.Items.Add(new ListItem("[Not specified]", ""));
  foreach (string key in col)
  {
    ddlCountry.Items.Add(new ListItem(key, dic[key]));
  }

  if (ddlCountry.SelectedIndex == 0 && Request.UserLanguages != null && Request.UserLanguages[0].Length == 5)
  {
    ddlCountry.SelectedValue = Request.UserLanguages[0].Substring(3);
  }

The method first adds all the countries from the CultureInfo class to a dictionary and then sorts it alphabetically. Last, it tries to retrieve the country of the browser so it can auto-select the visitors country. There might be a prettier way to sort a dictionary, but this one works.

* $4.95/month BlogEngine.net Hosting – Click Here!

Comments (9) -

Code Odyssey &#187; Ett annat s&#228;tt att lista l&#228;nder med .NET
Code Odyssey » Ett annat sätt att lista länder med .NET Sweden
5/27/2007 5:24:54 PM #

[…] Typiskt. Precis när man kämpat med att få ut en lista över länder i alfabetisk ordning så är det nån annan som gör precis samma sak. […]

Jesper Lind
Jesper Lind Sweden
5/27/2007 5:28:14 PM #

Sorry, the post before was supposted to be a trackback to my site, but the link did not appear. I have also published a simular function on my blog, but yours seems a bit better. Thanks!

You can see my solution here: http://codeodyssey.se/blog.aspx?id=287

Justin Th
Justin Th United Kingdom
6/4/2007 7:45:25 PM #

Hi Mads,

Great tip for getting a country list! By the way, you could use a SortedDictionary<TKey, TValue> (or the SortedList generic class -- which is very similiar) to get your sorted key value pairs without having to have a seperate list.

CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
SortedDictionary<string, string> regionLookup = new SortedDictionary<string, string>(StringComparer.Ordinal);
foreach (CultureInfo cultInfo in cultures)
{                    
    RegionInfo regionInfo = new RegionInfo(cultInfo.LCID);
    if (!regionLookup.ContainsKey(regionInfo.EnglishName))
    {
        regionLookup.Add(regionInfo.EnglishName, regionInfo.TwoLetterISORegionName);
    }                    
}
CountryList.DataTextField = "Key";
CountryList.DataValueField = "Value";
CountryList.DataSource = regionLookup;
CountryList.DataBind();

Chantal
Chantal Canada
9/24/2007 7:35:55 PM #

This is awesome, thanks for posting this!

Kevin Hazzard, MVP
Kevin Hazzard, MVP United States
8/4/2008 11:41:05 AM #

Hello Mads,

I have readers of my blog in China who want to know why the Chinese flag is not in the dropdown list. In BlogEngine.NET, a block of code in CommentView.ascx.cs is responsible for this:


foreach (CultureInfo ci in
   CultureInfo.GetCultures(
   CultureTypes.SpecificCultures))
   { /* ... */}


I created a 16x11 flag image called ZH.png and placed it in the flags folder. But apparently, if the ZH (Chinese) culture is not available on the host machine, it won't matter anyway. Is there something I'm missing, here.

If the Chinese culture is not available on the host machine, what can I do?

Thanks,

Kevin

Mads Kristensen
Mads Kristensen Denmark
8/4/2008 12:07:13 PM #

@Kevin,

That's because China is called People's Republic of China and it is in fact on the list.

Kevin Hazzard, MVP
Kevin Hazzard, MVP United States
8/4/2008 12:23:51 PM #

I totally missed that, Mads! So did my readers. I appreciate the quick follow-up.

Tak,

Kevin

Fenil Desai, MCP
Fenil Desai, MCP India
8/5/2008 11:50:11 AM #

Similar to the country list can we use CultureInfo class for state & city dropdown?

Richard
Richard United States
11/19/2008 11:50:36 PM #

Careful, this does not provide a complete list of countries in the world. Some examples of countries not provided in the list are: Benin, Burkina Faso, Guyana, Tuvalu, Uganda and more.

Small countries, but some person with internet access undoubtedly lives there! Also, don't know why 'Caribbean' is listed as a country - its more like a region of the world. Also Puerto Rico is listed (which is technically a US Terrioty) but Guam and the US Virgin Islands (other US Territories) are not listed.

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.