Billy101
Billy101

Reputation: 1

How to populate a DropDownListBox with the values of an Array

I need to populate the DropDownListBox with an array but i am having some problems.

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

That is what I currently have. However, every time I select an item from the DropDownListBox, it adds 9 more values.

Here is an example of what is shown in the dropdownlistbox when I select an item for the first time.

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

The values in the array will keep on adding on each time I select one. Any help would be greatly appreciated. Thank you!

Upvotes: 0

Views: 757

Answers (3)

ChaosOverlord
ChaosOverlord

Reputation: 56

Perhaps you are calling the Page_Load method from elsewhere?

KnockKnocks answer isnt bad, but you might also use a different for each structure

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

Instead of that, I suggest this, because its a bit easier to read

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

Upvotes: 0

Topman
Topman

Reputation: 336

following could help friend. The following code is for the combobox.

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

The following code is for the 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

Upvotes: 0

Icepickle
Icepickle

Reputation: 12806

Use the DataSource + DataBind methods, no need to add everything one per one

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

Upvotes: 1

Related Questions