Thursday, March 24, 2016

Get all countries from System.Globalization namespace and fill dropdown in asp.net

In this article I am going to explain how to get all countries list using system.globalization and bind to dropdownlist in asp.net using C# and vb.net.


Description:
System.Globalization namespace contains classes that define culture-related information, including language, country/region, calendars in use, and format patterns for dates, currency, and numbers, and sort order for strings.
 Implementation:
HTML Markup:
  <fieldset style="width:50%">
    <legend>Bind Dropdownlist using System.Globalization</legend>
    Select Country:<asp:DropDownList ID="ddlcountry" runat="server"> </asp:DropDownList>
    </fieldset>

First of all import the namespace
C# code:
using System.Globalization;

VB.net Code:
Imports System.Globalization

Get countries list
Create method to get countries list and call the method page load.
C# code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetAllCountry();
        }
    }

public void GetAllCountry()
    {
        try
        {
            List<string> listcountry = new List<string>();
            CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
            foreach (CultureInfo cinfo in cultures)
            {
                RegionInfo Rinfo = new RegionInfo(cinfo.LCID);

                if (!listcountry.Contains(Rinfo.EnglishName))
                {
                    listcountry.Add(Rinfo.EnglishName);
                }
            }
            listcountry.Sort();
            ddlcountry.DataSource = listcountry;
            ddlcountry.DataBind();
            ddlcountry.Items.Insert(0, new ListItem("--Select Country--""0"));
        }
        catch (Exception ex)
        {
        }
    }

VB.net Code:
  Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgsHandles Me.Load
        If Not IsPostBack Then
            GetAllCountry()
        End If
    End Sub

Public Sub GetAllCountry()
        Try
            Dim listcountry As New List(Of String)()
            Dim cultures As CultureInfo() = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
            For Each cinfo As CultureInfo In cultures
                Dim Rinfo As New RegionInfo(cinfo.LCID)
                If Not listcountry.Contains(Rinfo.EnglishName) Then
                    listcountry.Add(Rinfo.EnglishName)
                End If
            Next
            listcountry.Sort()
            ddlcountry.DataSource = listcountry
            ddlcountry.DataBind()
            ddlcountry.Items.Insert(0, New ListItem("--Select Country--""0"))
        Catch ex As Exception
        End Try
    End Sub

No comments:

Post a Comment