Get Countries list from CultureInfo class

By Jatin Prajapati

How to get all country names right inside from .NET Framework. We can get all country names from CultureInfo class.

Many times we need to list out country names on our web sites. For that we use SQL Server data table or pre-written XML file for this. Few of us know that we can get all country names right from .NET Framework itself. Yes, the CultureInfo class of .NET Framework provides us all the country names. So, see the below example....

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Collections.Generic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SortedDictionary<string, string> countries = new SortedDictionary<string, string>();            
            CultureInfo[] cultureInfos = CultureInfo.GetCultures(CultureTypes.AllCultures);
            foreach (CultureInfo culture in cultureInfos)
            {
                try
                {
                    RegionInfo regionInfo = new RegionInfo(culture.LCID);
                    if (!(countries.ContainsKey(regionInfo.EnglishName)))
                        countries.Add(regionInfo.EnglishName, regionInfo.EnglishName);
                }
                catch { }
            }

            foreach (KeyValuePair<string,string> value in countries)
                ddlCountries.Items.Add(new ListItem(value.Value));
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Countries</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddlCountries" runat="server"></asp:DropDownList>
    </div>
    </form>
</body>
</html>

Get Countries list from CultureInfo class  (2720 Views)