问题
I have a large window with a little under 200 controls/variables to worry about. Many of them are similar, so I am wondering if instead of repeatedly calling each one individually I can concatenate their names.
I'll make an example:
I have 5 pieces of data that I'm worried about: Red, Orange, Yellow, Green, Blue.
Each one of these will have a label that needs to be made visible, a textbox that needs to be made visible, and a string that contains the text in the textbox:
lblRed.Visible = True
txtRed.Visible = True
strRed = txtRed.Text
Instead of listing this for every one of those 5 pieces of data, is there a way that I could make some sort of array to loop through that could concatenate these variable names?
Dim list As New List(Of String)(New String() {"Red", "Orange", "Yellow", "Green", "Blue"})
Dim i As Integer = 0
Do while i < list.count
lbl + list(i) + .Visible = True
txt + list(i) + .Visible = True
str + list(i) = txt + list(i) + .Text
i = i+1
Loop
I know that the above code doesn't work, but I wanted to give you the basic idea of what I wanted to do. Does this look feasible?
回答1:
http://msdn.microsoft.com/en-us/library/7e4daa9c(v=vs.71).aspx
Using the controls collection:
Dim i As Integer
i = 1
Me.Controls("Textbox" & i).Text = "TEST"
so
Me.controls("lbl" & list(i)).Visible = true
Keep in mind that when concatenating items, '+' will work on strings and not integers. You might want to always use '&' when concatenating
回答2:
Another way is to use a select-case block for each type of control. Something like this:
Private Sub EnableControls()
For Each c As Control In Me.Controls
Select Case c.GetType
Case GetType(TextBox)
c.Visible = True
Select Case c.Name.Substring(3)
Case "Red"
strRed = c.Text
Case "Orange"
strOrange = c.Text
Case "Yellow"
'and so on
End Select
Case GetType(Label)
c.Visible = True
End Select
Next
End Sub
回答3:
Check out the information here:
http://msdn.microsoft.com/en-us/library/axt1ctd9.aspx
I'm sure someone may find something slightly more eloquent than this, but this should achieve your desired result. You'll need the below import:
Imports System.Reflection
If you use properties to access your variables, you can use reflection to grab them by name:
'Define these with getters/setters/private vars
Private Property strRed as String
Private Property strOrange as String
Private Property strYellow as String
Private Property strGreen as String
Private Property strBlue as String
For each color as String in list
If Me.Controls.Count > 1 Then
'Should really check for existence here, but it's just an example.
Me.Controls("lbl" & color).Visible = True
Dim tbx as TextBox = Me.Controls("txt" & color)
tbx.Visible = True
Dim propInfo as PropertyInfo = Me.GetType.GetProperty("str" & color)
propInfo.SetValue(Me, tbx.Text, Nothing)
End If
Next
来源:https://stackoverflow.com/questions/17578308/concatenate-variable-names-in-vb