IntroductionIn this article, i will show to how to get list of countries names using CultureInfo in ASP.NET.When you are work with online web site, you may want to get list of country names and add or bind into dropdownlist to choice by visitors or users.So I have done same things to my project, here would like to share with you. ImplementationLet's create a web project using visual studio and then drag and drop or add a drop down list into the page, html code will be following, Html Code <form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlLocation" runat="server"></asp:DropDownList>
</div>
</form>Now i'm going to add server side code to get the list of countries name.before start write code, you have to add namespace, using System.Globalization; Once you are add the above name space,lets write code as like following, using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> Country = GetCountryList();
var sortedCountry = from c in Country orderby c select c;
ddlLocation.DataSource = sortedCountry;
ddlLocation.DataBind();
ddlLocation.Items.Insert(0, "Select");
sortedCountry = null; Country = null;
}
}
public List<string> GetCountryList()
{
List<string> list = new List<string>();
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;
}
}Here i have used CultureInfo to get all region information.and then I'm adding each countries name into the string based generic list object finally returning list of counties from GetCountryList method. List<string> list = new List<string>();
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;And then in the page load event,only first load page, i have used LINQ to select countries name in sort order and bind to drop down list . Note:if you not familiar with LINQ, please read this articles to learn. List<string> Country = GetCountryList();
var sortedCountry = from c in Country orderby c select c;
ddlLocation.DataSource = sortedCountry;
ddlLocation.DataBind();That's all. hopes help to all. ConclusionIn this article, you learned to how to get list of countries names using CultureInfo class in ASP.NET.thank you for reading. please post your all comments. |