使用循环将整数填充到下拉列表

时间:2014-01-30 17:19:57

标签: asp.net vb.net list loops populate

无法弄清楚为什么我的程序不会使用循环填充 DropDownList

到目前为止,我已尝试过这两种情况:

'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

我也尝试使用.Add()功能而不是插入:

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

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

3 个答案:

答案 0 :(得分:2)

不确定为什么需要Index,但此代码可以使用:

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

答案 1 :(得分:1)

我个人是 For...Next 语句的粉丝,其中包含递减的 Step 参数。

  

可选。数字表达式。计数器的数量   每次循环都会增加。

你的例子是:

Dim currentYear = Date.Now.Year

For year = currentYear To currentYear - 100 Step -1

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

Next

答案 2 :(得分:0)

替换它:

DropDownListYear.Items.Insert(Index, CurYear)

使用:

DropDownListYear.Items.Insert(Index, new ListItem(CurYear.ToString(), CurYear.ToString()))