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

indradeo
 
on Oct 19, 2020 06:09 AM
1247 Views

how to pass current month and next month in dropdownlist in aspx c#

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Oct 19, 2020 06:10 AM
on Nov 02, 2020 11:49 PM

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.Month.ToString(),
            Value = currentDate.Month.ToString()
        });
        items.Add(new ListItem
        {
            Text = currentDate.AddMonths(1).Month.ToString(),
            Value = currentDate.AddMonths(1).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.Month.ToString(),
            .Value = currentDate.Month.ToString()
        })
        items.Add(New ListItem With {
            .Text = currentDate.AddMonths(1).Month.ToString(),
            .Value = currentDate.AddMonths(1).Month.ToString()
        })
        ddlMonths.DataSource = items
        ddlMonths.DataTextField = "Text"
        ddlMonths.DataValueField = "Value"
        ddlMonths.DataBind()
    End If
End Sub