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.

Comments


Comments are closed