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.
Populate selectlist with latest 5 years
Asked Answered
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.Today –
Eggshell
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;
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);
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
© 2022 - 2024 — McMap. All rights reserved.