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

indradeo
 
on Nov 01, 2020 10:49 PM
Sample_112081.zip
2583 Views

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

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 02, 2020 04:26 AM

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