Question

Can't figure out why my program wont populate my DropDownList using a loop.

So far I've tried these two scenarios:

'Fill in the year box from current year to 100 years ago.
'(Safe to assume no one over 100 will be signing up for site)

Dim CurYear As Integer = Date.Now.Year
Dim CurYearMinus100 As Integer = CurYear - 100
Dim Index As Integer = 0

Do While CurYear >= CurYearMinus100
    DropDownListYear.Items.Insert(Index, CurYear)
    Index += 1
    CurYear -= 1
Loop

I've also tried using the .Add() functionality instead of insert:

Dim CurYear As Integer = Date.Now.Year
Dim CurYearMinus100 As Integer = CurYear - 100

Do While CurYear >= CurYearMinus100
    DropDownListYear.Items.Add(Index)
    CurYear -= 1
Loop
Was it helpful?

Solution

Not sure why you need Index, but this code will work:

Dim CurYear As Integer = Date.Now.Year
Dim CurYearMinus100 As Integer = CurYear - 100

Do While CurYear >= CurYearMinus100
    DropDownListYear.Items.Add(New ListItem(CurYear.ToString(), CurYear.ToString()))
    CurYear -= 1
Loop

OTHER TIPS

I personally am a fan of the For...Next statement with a decrementing Step argument.

Optional. Numeric expression. The amount by which counter is incremented each time through the loop.

Your example would be:

Dim currentYear = Date.Now.Year

For year = currentYear To currentYear - 100 Step -1

   DropDownListYear.Items.Add(New ListItem(year.ToString(), year.ToString()))

Next

Replace this:

DropDownListYear.Items.Insert(Index, CurYear)

With:

DropDownListYear.Items.Insert(Index, new ListItem(CurYear.ToString(), CurYear.ToString()))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top