Bind countries from CultureInfo class in C#

by Mads Kristensen 28. May 2007 00:11

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.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

ASP.NET

Comments

5/28/2007 2:24:54 AM #

Code Odyssey » Ett annat sätt att lista länder med .NET

[…] 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. […]

Code Odyssey » Ett annat sätt att lista länder med .NET Sweden |

5/28/2007 2:28:14 AM #

Jesper Lind

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

Jesper Lind Sweden |

6/5/2007 4:45:25 AM #

Justin Th

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();

Justin Th United Kingdom |

9/25/2007 4:35:55 AM #

Chantal

This is awesome, thanks for posting this!

Chantal Canada |

8/4/2008 8:41:05 PM #

Kevin Hazzard, MVP

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

Kevin Hazzard, MVP United States |

8/4/2008 9:07:13 PM #

Mads Kristensen

@Kevin,

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

Mads Kristensen Denmark |

8/4/2008 9:23:51 PM #

Kevin Hazzard, MVP

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

Tak,

Kevin

Kevin Hazzard, MVP United States |

8/5/2008 8:50:11 PM #

Fenil Desai, MCP

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

Fenil Desai, MCP India |

11/20/2008 8:50:36 AM #

Richard

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.

Richard United States |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008