fusioninternet
asked on
Populating dropdownlist in pageload dupliactes items
Hi, I'm want to populate a dropdownlist with this year and the next 5 years.
So in the pageload I have added the code as shown in the snippet.
This I had hoped would give me the list 2008,2009,2010,2011,2012,2 013 but it actually only gives me a list of 2013 six times.
Can't quite work it out any help appreciated.
So in the pageload I have added the code as shown in the snippet.
This I had hoped would give me the list 2008,2009,2010,2011,2012,2
Can't quite work it out any help appreciated.
DateTime dt = DateTime.Now;
int year = dt.Year;
ListItem addYear = new ListItem();
for (int i = 0; i <= 5; i++)
{
addYear.Value = Convert.ToString(year + i);
addYear.Text = Convert.ToString(year + i);
StartYear.Items.Add(addYear);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
if you are declaring value and text to be the same thing, it is redundant. Also, if you are declaring them both to be the same, you do not need to declare them as items, you can directly add them as strings. A couple tricks to make things easier :)
ASKER
Nice one, that did the trick
Thanks for the second reply, I did realise that I would only need to enter it once, but I am planning to have the text as 2008 and the value as 08., would this cause a major upset to the way you've just shown me?
Cheers
Steve
Thanks for the second reply, I did realise that I would only need to enter it once, but I am planning to have the text as 2008 and the value as 08., would this cause a major upset to the way you've just shown me?
Cheers
Steve
to add them in seperately do like pratima said:
ListItem addYear = new ListItem();
addYear.Value = Convert.ToString(year + i).SubString(2,2);
addYear.Text = Convert.ToString(year + i);
StartYear.Items.Add(addYear);
or to keep it small again:
for (int i = 0; i < 6; i++)
StartYear.Items.Add(new ListItem(DateTime.Now.AddYears(i).Year.ToString(), DateTime.Now.AddYears(i).Year.ToString().Substring(2, 2)));
DateTime dt = DateTime.Now;
int year = dt.Year;
for (int i = 0; i <= 5; i++)
{
ListItem addYear = new ListItem();
addYear.Value = Convert.ToString(year + i);
addYear.Text = Convert.ToString(year + i);
StartYear.Items.Add(addYea