CSharpFeeds - All your C# feeds in one place.

Sponsors

Sunday, May 27, 2007

Bind countries from CultureInfo class in C#

by via .NET Slave on 5/27/2007 6:11:00 PM

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.

email it!bookmark it!digg it!

Original Post: Bind countries from CultureInfo class in C#

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us