Question Naming Text box using index

onli.onl

New member
Joined
Dec 4, 2013
Messages
1
Programming Experience
Beginner
Hi,

I am trying to use index to assign 10, 30, 50, 70, and 90 to some list boxes names "listbox1", "listbox2", "listbox3", "listbox4", "listbox5".

Please look at this simple code:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Class Form1
Dim MyNumbers(4) As Double
Dim listbox(i) As ListBox
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


For i As Integer = 0 To 4
MyNumbers(i) = 10 + 20 * i
ListBox(i).Items.Add(MyNumbers(i))


Next i
End Sub
End Class
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

The error is "Index was outside the bounds of the array." and it does not get ListBox(1) as ListBox1! What should I do?

Thank you,
Onli
 

IanRyder

Well-known member
Joined
Sep 9, 2012
Messages
1,130
Location
Healing, NE Lincs, UK
Programming Experience
10+
Hi and welcome to the Forum,

Your specific issue is that you have created an Array of ListBoxes but you have not actually populated that Array with ListBoxes. All you have done at the moment is declare a container that can hold ListBoxes.

So, assuming that you are using a current version of the .NET Framework and NOT version 1.0 then you can use the Repeat Method of the Enumerable Class to populate the Array with ListBoxes at the time you declare it. i.e:-

Dim listbox() As ListBox = Enumerable.Repeat(New ListBox, 5).ToArray


That said, are you actually trying to populate ListBox controls that already exist on your form? If so, then you do not need your Array and you need to access the Controls collection of the Form to populate the ListBoxes. i.e:-

For i As Integer = 0 To 4
  MyNumbers(i) = 10 + 20 * I
  Dim currentListBox As ListBox = DirectCast(Me.Controls("ListBox" & i + 1), ListBox)
  currentListBox.Items.Add(MyNumbers(i))
Next


Hope that helps.

Cheers,

Ian
 
Top Bottom