Reputation: 1338
I have a bunch of variables named "panel_1", panel_2", etc and I want to change the height of all of the controls using a loop rather than naming each one.
Currently I use
Dim panel_1 as new panel
Dim panel_2 as new panel
Dim panel_3 as new panel
panel_1.height = 100
panel_2.height = 100
panel_3.height = 100
How can I do it this way?
for x as integer = 0 to 1000
panel_[x].height = 100
next
thanks.
Upvotes: 0
Views: 7871
Reputation: 2872
Just loop through how many panels you want (In your case 3) & create a new panel on each iteration, setting the height & name programmatically.
For i = 0 To 3
Dim panel As New Panel
panel.Name = "panel" & i
panel.Height = 100
Next
Upvotes: 0
Reputation: 38905
My preferred method is to (usually) store the controls names:
Dim panels as new List(Of String)
For n As integer = 0 to X
Dim pnl As New Panel
'... set values
panels.Add(pnl.Name)
Controls.Add(pnl)
Next n
To reference one:
Controls(panels(IndexofOneYouWant).Height = 100
Since you dynamically created the control, you could also be deleting them on occasion. In that case the List is not holding a reference to them when you go to remove one. If they remain once created, then a List(of Panel)
is easier and better.
Upvotes: 0
Reputation: 21495
You can't do such variable access in VB.NET.
Instead of defining three variables, define an array or list
Dim panels as new List(Of Panel)
panels.Add(new Panel())
panels.Add(new Panel())
for x as integer = 0 to 1000
Dim p as new Panel
p.height = 100
panels.Add(p)
panels(x).width = 150
next
Upvotes: 0
Reputation: 43743
If this is a WinForm project, all of the controls are included in the form's Controls
collection, which is accessible by name, like this:
For x As Integer = 0 to 1000
Me.Controls("panel_" & i.ToString()).height = 100
Next
However, be aware that the form's Controls
collection only contains the controls that are added directly to the form. If you have controls that are inside another container control, you will need to access them through that container's Controls
property, for instance:
For x As Integer = 0 to 1000
MyContainer.Controls("panel_" & i.ToString()).height = 100
Next
However, accessing controls by their string name may be something that you wish to avoid, since it can lead to unintended consequences down the road. As other's have suggested, it may be better to store the list of panels in a List(Of Panel) variable, which only contains the specific panel controls to which the resizing logic applies, like this:
Dim autoResizePanels As New List(Of Panel)({panel1, panel2, panel3})
Then, you can loop through them easily, like this:
For Each i As Panel In autoResizePanels
i.height = 100
Next
Upvotes: 3