4

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
ekad
  • 14,436
  • 26
  • 44
  • 46
Vince
  • 2,596
  • 11
  • 43
  • 76

3 Answers3

3

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
ekad
  • 14,436
  • 26
  • 44
  • 46
1

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
Code Maverick
  • 20,171
  • 12
  • 62
  • 114
0

Replace this:

DropDownListYear.Items.Insert(Index, CurYear)

With:

DropDownListYear.Items.Insert(Index, new ListItem(CurYear.ToString(), CurYear.ToString()))
Irfan TahirKheli
  • 3,652
  • 1
  • 22
  • 36