如何使用Array的值填充DropDownListBox

时间:2014-11-25 22:09:54

标签: arrays vb.net drop-down-menu

我需要使用数组填充DropDownListBox,但我遇到了一些问题。

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

    Dim arrEmployeeID() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}
    Dim x As Integer

        For x = LBound(arrEmployeeID) To UBound(arrEmployeeID)
            ddlEmployeeID.Items.Add(arrEmployeeID(x))
        Next
End Sub

这就是我现在拥有的。但是,每次我从DropDownListBox中选择一个项目时,它都会再添加9个值。

以下是我第一次选择项目时下拉列表框中显示内容的示例。

1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9

每次选择数组时,数组中的值将继续添加。 任何帮助将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:1)

使用DataSource + DataBind方法,无需每个人添加一个

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim arrEmployeeID() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}

    If Not IsPostBack Then
        'no postback, so set the datasource, and bind it'
        DropDownList1.DataSource = arrEmployeeID
        DropDownList1.DataBind()
    End If
End Sub

答案 1 :(得分:0)

以下可以帮助朋友。 以下代码用于组合框。

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    Dim arrEmployeeID() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}

    cboBox.DropDownStyle = ComboBoxStyle.DropDownList 'It allows only to use the drop down list values or do not allow to edit the values.
    cboBox.DataSource = arrEmployeeID
End Sub

以下代码适用于ListBox

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    Dim arrEmployeeID() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}

    'Make sure that the listbox is empty 
    lstBox.Items.Clear()

    For i = 0 To arrEmployeeID.Length - 1
        lstBox.Items.Add(arrEmployeeID(i.ToString))
   Next
End Sub

答案 2 :(得分:0)

也许您正在从其他地方调用Page_Load方法?

KnockKnocks的答案并不错,但您可能也会为每个结构使用不同的

For i = 0 To arrEmployeeID.Length - 1
    lstBox.Items.Add(arrEmployeeID(i.ToString))
Next

而不是那样,我建议这样做,因为它更容易阅读

For Each item As Integer In arrEmployeeID
 lstBox.Items.Add(arrEmployeeID(i.ToString))
Next