I have a dropdownlist in ASP.NET Webforms that I want to calculate how many years ago a certain year was.
In the first line 2002 is the current year -9 and has to be the value, and 9 is the text that is visibel and shows how many years ago 2002 was.
2002 9
2003 8
2004 7
2005 6
2006 5
2007 4
2008 3
2009 2
2010 1
2011 0
And I want 5 to be the preselected. How Do I do that? First of I dont know how to add a hidden Value (ex. 2002 to the visibel 9).
This is my start... Not far, I know...
{
int CT = DateTime.Now.Year;
int CT10 = CT - 10;
for (int i = CT10; i <= CT; i++)
{
ddlBirthYear.Items.Add(i.ToString());
}
}
You can use a ListItem to add a text and value
You can select that with
So your loop will look like this:
After you've added your items just use the
SelectedIndex
property to preselect a value 5 years ago like so:SelectedIndex
property is is pointing to an index of an item in the list.If you want to select a particular year by it's value you need to use
SelectedValue
property.