Asp.net: populate dropdownlist with months name | ASPMANTRA | Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server AND WCF snippets and tutorial

Asp.net: populate dropdownlist with months name

In this article I am going to explain how to populate dropdownlist with months name 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>Populate Dropdownlist with Months Names</legend>
    Select Country:<asp:DropDownList ID="ddlmonth" runat="server" AutoPostBack="true">
    <asp:ListItem Value="0">--Select--</asp:ListItem>
    </asp:DropDownList>
    </fieldset>

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

VB.net 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)
        {
            GetMonthName();
        }
    }

public void GetMonthName()
    {
        try
        {
            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>");
    }

VB.net Code:
  Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            GetMonthName()
        End If
    End Sub
    Public Sub GetMonthName()
        Try
            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()))
            Next
        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


Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget