Populate selectlist with latest 5 years
Asked Answered
G

3

8

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.

Guck answered 19/7, 2011 at 8:53 Comment(2)
Discover what year it is now, display that plus previous four years. Which part do you have a problem with?Tongs
Any attempts at solving this? Hint: 'DateTime.TodayEggshell
O
12

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;
Ornithology answered 19/7, 2011 at 8:54 Comment(0)
I
1

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);
Irregular answered 19/7, 2011 at 8:55 Comment(0)
R
0

Something like this:

List<int> last5Years = new List<int>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 5; i < currentYear; i++)
{
    last5Years.Add(i);
}
//databind here
Rudyrudyard answered 19/7, 2011 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.