Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate selectlist with latest 5 years

How am I able to create a list with the last 5 years in it, such as the years 2011 to 2007. I don't want to hard code the years, but I want the most recent 5 years based on the current year.

like image 574
newbie_86 Avatar asked Jul 19 '11 08:07

newbie_86


2 Answers

Put the last 5 years in your view model and bind to that:

var last5Years = from n in Enumerable.Range(0,5)
                 select DateTime.Now.Year - n;
like image 76
driis Avatar answered Nov 08 '22 09:11

driis


DateTime.Now.Year will give you the current year, then you can use a loop

DateTime dt = DateTime.Now;
for(int i = 0; i < 5; i++)
   list.Add(dt.Now.Year - i);
like image 32
musefan Avatar answered Nov 08 '22 08:11

musefan