Reputation: 409
I have a group of 8 TextBoxes
in a WinForm
and I've created an object array for them to be contained. In the initialization of the Form
, I want to set each TextBox.text
to Environ("USERPROFILE") & "\Documents"
to show the default file-path for each box. These boxes are used for displaying which file is to be loaded based on user input.
Currently the code looks like this:
Public Sub New()
InitializeComponent()
BWGPTextBox.Text = Environ("USERPROFILE") & "\Documents"
BWBRTextBox.Text = Environ("USERPROFILE") & "\Documents"
ChGPTextBox.Text = Environ("USERPROFILE") & "\Documents"
ChBRTextBox.Text = Environ("USERPROFILE") & "\Documents"
CCGPTextBox.Text = Environ("USERPROFILE") & "\Documents"
CCBRTextBox.Text = Environ("USERPROFILE") & "\Documents"
PPGPTextBox.Text = Environ("USERPROFILE") & "\Documents"
PPBRTextBox.Text = Environ("USERPROFILE") & "\Documents"
End Sub
Is there a way I can have it operate within a For Loop (similar to below, except this does not work) to define each box? This way I can also modify each box uniformly, such as [Excel.Application].[Excel.Workbook].Open(TextBoxesList(x).Text)
Public Sub New()
InitializeComponent()
Dim TextBoxesList As Object = {BWGPTextBox, BWBRTextBox, _
ChBRTextBox, ChGPTextBox, _
CCGPTextBox, CCBRTextBox, _
PPGPTextBox, PPBRTextBox}
For Each x In TextBoxesList
TextBoxesList(x).GetType() ' = Environ("USERPROFILE") & "\Documents"
Next
End Sub
Upvotes: 0
Views: 62
Reputation: 38905
Storing specific types As Object is often a mistake since it hides the real type being stored:
Dim TextBoxesList As Object = {BWGPTextBox, BWBRTextBox,
ChBRTextBox, ChGPTextBox,
CCGPTextBox, CCBRTextBox,
PPGPTextBox, PPBRTextBox}
The resulting array stores Objects which prevents you from accessing TextBox specific properties. Start with a typed array:
' DECLARE the array at the form level:
Private TextBoxesList As TextBox()
....
' initialize it AFTER the constructor runs:
TextBoxesList = {BWGPTextBox, BWBRTextBox,
ChBRTextBox, ChGPTextBox,
CCGPTextBox, CCBRTextBox,
PPGPTextBox, PPBRTextBox}
' then loop:
For Each tb As TextBox in TextBoxesList
tb.Text = "foo"
Next
Stored and iterated As TextBox
allows TextBox
properties to be easily accessed. You can also loop by index:
For n As Int32 = 0 to TextBoxesList.Count-1
TextBoxesList(n).Text = "foo"
Next
Upvotes: 2