Get a SortedList of Years

By September 29, 2009 asp.net

So this is the first of what I hope will be many code samples I’ve either written myself or (more likely) come across during my travels around the Web.

Most of these routines or functions find there way into my common libraries and most web projects.  They won’t be the best but they won’t be the worst either. Feel free to suggest improvements or to use the code how you see fit.

The first is a really basic function to return a SortedList of years you can use in dropdown lists and the like.

SortedList years = new SortedList();
years[DateTime.Now.Year] = DateTime.Now.Year;

for (int i = -10; i<numYears; i++)
{
	years[DateTime.Now.AddYears(i).Year] = DateTime.Now.AddYears(i).Year;
}
return years;

The key and the value is the same so if you are using it to bind to a dropdown list, it would look like this in the page load event:

myDropDownList.DataSource = GetYears(5);
myDropDownList.DataValueField="Key";
myDropDownList.DataTextField="Value";
myDropDownList.DataBind();

This comes in handy when you need a revolving list of years within a certain date range.

Have fun.