vb.net 在运行时以编程方式将值添加到下拉列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16731161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:43:37  来源:igfitidea点击:

Add values to dropdown list programatically at run time

asp.netvb.net

提问by ubaid ashraf

I am trying to change the list item values of a dropdown list based on values of an other dropdown list. The list values of drpAdult range from 0-9 and list values of drpInfant range from 0-(Value of drpAdult selected).

我正在尝试根据其他下拉列表的值更改下拉列表的列表项值。drpAdult 的列表值范围为 0-9,drpInfant 的列表值范围为 0-(选择了 drpAdult 的值)。

So, for example, if I select 5 in the drpAdult dropdown, the range of list item values of drpInfant will be from 0-5.

因此,例如,如果我在 drpAdult 下拉列表中选择 5,则 drpInfant 的列表项值范围将是 0-5。

I have written the code below, but it is not populating the values in the drpInfant dropdown, which I am trying to insert on drpAdult_SelectedIndexChanged event.

我已经编写了下面的代码,但它没有填充 drpInfant 下拉列表中的值,我试图在 drpAdult_SelectedIndexChanged 事件上插入该值。

Protected Sub drpAdult_SelectedIndexChanged(ByVal sender As Object, 
 ByVal e As EventArgs) Handles drpAdult.SelectedIndexChanged  

    Dim count As Integer    
    count = drpAdult.Items.Count
    Dim i As Integer
    i = 0
     While count > 0
        i = i + 1

        drpInfant.Items.Add(New ListItem(i, i))
        count = count - 1

    End While
End Sub

What might cause this problem, and how can I resolve it?

什么可能导致此问题,我该如何解决?

采纳答案by Tim Schmelter

Not sure what "is not working"means, but this seems to be easier anyway:

不确定“不起作用”是什么意思,但这似乎更容易:

Dim newCount = drpAdult.Items.Count + 1
For i As Int32 = 0 To newCount
    Dim newItem As New ListItem(i.ToString, i.ToString)
    drpInfant.Items.Add(newItem)
Next

回答by Patrick Allwood

Something along these lines...

沿着这些路线的东西......

drpInfant.Items.Clear()
dim n as Integer
Integer.TryParse(drpAdult.SelectedValue, n)

For i as integer = 1 to n
  if n < i Then Exit For 'it's not fun when this condition happens in VB
  drpInfant.Items.Add(New ListItem(i, i))
Next

回答by Santosh Panda

You can try this. I have tested this & working fine:

你可以试试这个。我已经测试过这个并且工作正常:

    Protected Sub drpAdult_SelectedIndexChanged(sender As Object, e As EventArgs)

    drpInfant.Items.Clear()

    Dim count As Integer = drpAdult.SelectedIndex
    Dim i As Integer = 0

    While count >= 0
        drpInfant.Items.Add(New ListItem(i.ToString(), i.ToString()))

        i = i + 1
        count = count - 1
    End While
End Sub