Populate DropDownList with current and previous month using C# and VB.Net in ASP.Net

Last Reply 27 days ago By dharmendr

Posted 28 days ago

how to display current and previous month in dropdown box using aspx c#.

You are viewing reply posted by: dharmendr 27 days ago.
Posted 27 days ago

Hi indradeo,

Refer below sample.

HTML

<asp:DropDownList runat="server" ID="ddlMonths">
</asp:DropDownList>

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DateTime currentDate = DateTime.Now;
        List<ListItem> items = new List<ListItem>();
        items.Add(new ListItem
        {
            Text = currentDate.AddMonths(-1).Month.ToString(),
            Value = currentDate.AddMonths(-1).Month.ToString()
        });
        items.Add(new ListItem
        {
            Text = currentDate.Month.ToString(),
            Value = currentDate.Month.ToString()
        });
        ddlMonths.DataSource = items;
        ddlMonths.DataTextField = "Text";
        ddlMonths.DataValueField = "Value";
        ddlMonths.DataBind();
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim currentDate As DateTime = DateTime.Now
        Dim items As List(Of ListItem) = New List(Of ListItem)()
        items.Add(New ListItem With {
            .Text = currentDate.AddMonths(-1).Month.ToString(),
            .Value = currentDate.AddMonths(-1).Month.ToString()
        })
        items.Add(New ListItem With {
            .Text = currentDate.Month.ToString(),
            .Value = currentDate.Month.ToString()
        })
        ddlMonths.DataSource = items
        ddlMonths.DataTextField = "Text"
        ddlMonths.DataValueField = "Value"
        ddlMonths.DataBind()
    End If
End Sub