Sunday, April 3, 2016

How to fill dropdownlist with months name using System.Globalization in

In this article I am going to explain how to fill dropdownlist with months name using System.Globalization in using C# and

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.

HTML Markup:
  <fieldset style="width:50%">
    <legend>Populate Dropdownlist with Months Names</legend>
    Select Country:<asp:DropDownList ID="ddlmonth" runat="server" AutoPostBack="true">
    <asp:ListItem Value="0">--Select--</asp:ListItem>

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

Get month’s name
Create method to get month’s name and call the method page load.
C# code:
protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)


public void GetMonthName()
            DateTimeFormatInfo dtinfo = DateTimeFormatInfo.GetInstance(null);
            for (int i = 1; i <= 12; i++)
                string monthname = dtinfo.GetMonthName(i);
                ddlmonth.Items.Add(new ListItem(monthname, i.ToString()));
        catch (Exception ex)
        { }
  protected void ddlmonth_SelectedIndexChanged(object sender, EventArgs e)
        Response.Write("<script>alert('Selected Month is : "+ ddlmonth.SelectedItem +"')</script>");
    } Code:
  Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
        End If
    End Sub
    Public Sub GetMonthName()
            Dim dtinfo As DateTimeFormatInfo = DateTimeFormatInfo.GetInstance(Nothing)
            For i As Integer = 1 To 12
                Dim monthname As String = dtinfo.GetMonthName(i)
                ddlmonth.Items.Add(New ListItem(monthname, i.ToString()))
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub ddlmonth_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ddlmonth.SelectedIndexChanged
        Response.Write("<script>alert('Selected Month is : " & ddlmonth.SelectedItem.ToString() & "')</script>")
    End Sub

No comments:

Post a Comment