Share Blog

Wednesday, August 12, 2015

Binding all countries to dropdownlist in Asp.net Using System.Globalization in C#


To get all countries in asp.net first open your aspx page and write the following code


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Bind_Country.aspx.cs" Inherits="Bind_Country" %>

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Binding all countries to dropdownlist in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <b>Select Country:</b>
        <asp:DropDownList ID="ddlcountry" runat="server">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>


Now add following namespaces in code behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;


After completion of Adding namespaces you need to write the code like as shown below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

public partial class Bind_Country : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<string> objcountries = new List<string>();
            CultureInfo[] objculture =CultureInfo.GetCultures(CultureTypes.SpecificCultures);
            foreach (CultureInfo getculture in objculture)
            {
                RegionInfo objregion = new RegionInfo(getculture.LCID);
                if (!(objcountries.Contains(objregion.EnglishName)))
                {
                    objcountries.Add(objregion.EnglishName);
                }
            }
            objcountries.Sort();
            ddlcountry.DataSource = objcountries;
            ddlcountry.DataBind();
        }


    }
}


Result




No comments:

Post a Comment