Thursday, October 7, 2010

Bind Windows Default Countries to a DropDownList in ASP.NET

How to get list of all countries and bind to a dropdown list in ASP.NET
Create an ASP.NET application and add a DropDownList to the page something like this.<asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList>

Now call this GetCountryList method on your page load that will bind and display countries in the DropDownList.

public List GetCountryList()
    {
      List list = new List();
      CultureInfo[] cultures =
                  CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures |
                  CultureTypes.SpecificCultures);
      foreach (CultureInfo info in cultures)
      {
          RegionInfo info2 = new RegionInfo(info.LCID);
          if (!list.Contains(info2.EnglishName))
          {
              list.Add(info2.EnglishName);
          }
      }
      return list;
    }
ddlLocation.DataSource = GetCountryList();
ddlLocation.DataBind();
ddlLocation.Items.Insert(0, "Select");

Note: Updated attachement contains code for orderby the list using LINQ.