Click here to Skip to main content
15,917,731 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two dropdown lists one is bind with year from current year +5 years. Once year selected automatically remaining months will be bind.

for example:

Year     Month
====     =====
2016     Nov
         Dec

Year     Month
====     =====
2017     Jan
         Feb
         Mar
         .
         .
         Nov
         Dec


What I have tried:

Bind Year:
 DropDownList1.DataSource = Enumerable.Range(DateTime.Now.Year, 5);
 DropDownList1.DataBind();

Bind Month:

  int remainingmonth = DateTime.Today.Month;
      
        DropDownList2.Items.Clear();
        
        for (int i = remainingmonth; i <= 12; i++)
         {
          DropDownList2.Items.Add(new System.Web.UI.WebControls.ListItem(DateTimeFormatInfo.CurrentInfo.GetMonthName(i) , i.ToString()));
         }
Posted
Updated 19-Nov-16 21:43pm
Comments
Richard MacCutchan 20-Nov-16 3:11am    
Very interesting; do you have a question?
shaprpuff 20-Nov-16 3:21am    
yes where to pass the selected year to bind the months

1 solution

Please check this
Design:
ASP.NET
<asp:DropDownList ID="ddlYear" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddlYear_SelectedIndexChanged"></asp:DropDownList>

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

Code:
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddlYear.DataSource = Enumerable.Range(DateTime.Now.Year, 5);
        ddlYear.DataBind();
        ddlYear.Items.Insert(0,"Please select");
    }
}

protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
{
    int remainingmonth = Convert.ToInt32(ddlYear.SelectedItem.Text) == DateTime.Today.Year ? DateTime.Today.Month : 1;

    ddlMonth.Items.Clear();

    for (int i = remainingmonth; i <= 12; i++)
    {
        ddlMonth.Items.Add(new System.Web.UI.WebControls.ListItem(DateTimeFormatInfo.CurrentInfo.GetMonthName(i), i.ToString()));
    }
}
 
Share this answer
 
Comments
shaprpuff 20-Nov-16 5:11am    
Thanks, it works "manu_dhobale" but please explian this line...

Convert.ToInt32(ddlYear.SelectedItem.Text) == DateTime.Today.Year ? DateTime.Today.Month : 1;
manu_dhobale 20-Nov-16 5:49am    
Its just a if statement, alternatively you can write is as
int selectedYear = Convert.ToInt32(ddlYear.SelectedItem.Text);
int remainingmonth = 0;
if (selectedYear == DateTime.Today.Year)
{
remainingmonth = DateTime.Today.Month;
}
else
{
remainingmonth = 1;// jan month
}
shaprpuff 20-Nov-16 6:05am    
Thanks you very much.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900