Creating listboxes "on the fly"

VonEhle

Active member
Joined
Feb 20, 2006
Messages
26
Programming Experience
Beginner
Let's say I ask the user for a number between 1 and 10, then they click a button. How would I then create that same number of listboxes to appear on a form? I know I could create them and make them visible after the number is entered, but I'm pretty sure that will create a ton of unnecessary code.

An example of what I tried:

VB.NET:
intPlayers = toInt16(txtHowMany.text)
 
For TotalPlayers = 1 to intPlayers
    dim lst as new listbox
lst.show()
 
after you created the New ListBox you set its properties (location etc) and add it to the containers Control collection. If the targeted container is directly on form you code: Me.Controls.Add(lst)
To add/remove event handlers dynamically use the AddHandler/RemoveHandler statements.
 
When I want to add something to these boxes later, how do I know what its name property is? Can they be named as they are created? lst1, lst2 etc...
 
Ok, new question on this topic.

I'm trying to add data to these listboxes now. Each listbox was named "lstPL" & intPlayers in a loop. I can't figure out how to reference these listboxes in a loop later on. What I have below in red doesn't work.

VB.NET:
While intDealCard <= 51
[COLOR=darkred]lstPL(intPlayers).[/COLOR]Items.Add(DealCards.ShuffleCards(intDealCard).numbers _
& DealCards.ShuffleCards(intDealCard).suit)
intDealCard += 1
EndWhile
 
You could create a collection of some sort, I would use Generic.List(of ListBox), and add the listbox to the collection as you create them. Then use the index of the collection to reference the individual listboxs.
VB.NET:
'll = listbox list
Dim ll As New Generic.List(Of ListBox)
'start at zero since the collection is zero-based
For TotalPlayers As Integer = 0 To intPlayers - 1
    Dim lst As New ListBox
    lst.Location = New Point(0, 0)
    AddHandler lst.SelectedIndexChanged, AddressOf someprocedure
    ll.Add(lst)
    Me.Controls.Add(lst)
Next
'referencing
'remember the List is zero-based so start at zero and go to 50
While intDealCard <= 50
    ll(intPlayers).Items.Add(DealCards.ShuffleCards(intDealCard).numbers _
      & DealCards.ShuffleCards(intDealCard).suit)
    intDealCard += 1
End While
 
You can access them directly by name:
VB.NET:
[SIZE=2][COLOR=#0000ff]
Dim[/COLOR][/SIZE][SIZE=2] lb [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] ListBox = [/SIZE][SIZE=2][COLOR=#0000ff]DirectCast[/COLOR][/SIZE][SIZE=2]([/SIZE][SIZE=2][COLOR=#0000ff]Me[/COLOR][/SIZE][SIZE=2].Controls([/SIZE][SIZE=2][COLOR=#a31515]"name"[/COLOR][/SIZE][SIZE=2]), ListBox)
[/SIZE]
 
Back
Top