Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to display last 5 years(Month-Year) in dropdown.

The format in the dropdown should display "Month-Year" (I want last 5 years values).
Posted

Use the below Code

C#
for (int innlop = 1; innlop <= 5; innlop++)
               DropDownList1.Items.Add(DateTime.Now.AddYears(innlop * -1).Year.ToString());



***

 
Share this answer
 
Comments
Un_NaMeD 3-Jan-12 2:27am    
Nice. My 5!
Rajesh Anuhya 3-Jan-12 2:46am    
Thanks
Instead of storing directly the month and the year, I'd prefer creating DateTime objects for each month. When the dropdown is filled the datetime could be formatted as needed but also the actual datetime object could be stored for later use and to avoid interpretation of the text in the dropdown. For example consider this:
C#
System.DateTime dtNow = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, 1);
while (dtNow >= System.DateTime.Now.AddYears(-5)) {
   dtNow.ToString("MMMM-yyyy"); // this would go to the dropdown as DataTextField
   dtNow; //This would go to the dropdown as a DataValueField
   dtNow = dtNow.AddMonths(-1);
}
 
Share this answer
 
Try this,

C#
int yr = 2012;
        string[] monthNames = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        for (int cnt = yr - 5; cnt < yr; cnt++)
        {
            for (int mth = 0; mth <= 11; mth++)
            {
                ddl_Years.Items.Add(monthNames[mth] + "-" + cnt.ToString());
            }
        }
        ddl_Years.Items.Insert(0, new ListItem("--Please Select--", "0"));
 
Share this answer
 
v2
Comments
Supriya Srivastav 3-Jan-12 5:16am    
what do you mean here by "current month-year"
do you want to restrict values not more than current month and year?
Explain?
Supriya Srivastav 3-Jan-12 7:42am    
use it,
string cur_Date = DateTime.Now.ToString("MMMM") + "-" + DateTime.Now.ToString("yyyy");
string[] monthNames = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
for (int cnt = 2006; cnt <= 2020; cnt++)
{
for (int mth = 0; mth <= 11; mth++)
{
string item = monthNames[mth] + "-" + cnt.ToString();
ddl_Years.Items.Add(new ListItem(item, item));
}
}
ddl_Years.Items.Insert(0, new ListItem("--Please Select--", "0"));
ddl_Years.SelectedValue = cur_Date;

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