我有一个大窗口,有一些不到200个控件/变量需要担心。其中许多是相似的,所以我想知道如果不是反复单独调用每一个,我可以连接他们的名字。
我会举个例子:
我有5件我担心的数据:红色,橙色,黄色,绿色,蓝色。
其中每一个都有一个需要显示的标签,一个需要显示的文本框,以及一个包含文本框中文本的字符串:
lblRed.Visible = True
txtRed.Visible = True
strRed = txtRed.Text
不是为这5个数据中的每一个列出这个,而是有一种方法可以使某些数组循环可以连接这些变量名吗?
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
我知道上面的代码不起作用,但我想告诉你我想做的基本想法。这看起来可行吗?
答案 0 :(得分:1)
http://msdn.microsoft.com/en-us/library/7e4daa9c(v=vs.71).aspx
使用控件集合:
Dim i As Integer
i = 1
Me.Controls("Textbox" & i).Text = "TEST"
所以
Me.controls("lbl" & list(i)).Visible = true
请记住,在连接项目时,“+”将用于字符串而不是整数。您可能希望始终使用'&amp;'连接时
答案 1 :(得分:0)
另一种方法是为每种类型的控件使用选择块。像这样:
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
答案 2 :(得分:0)
查看此处的信息:
http://msdn.microsoft.com/en-us/library/axt1ctd9.aspx
我确信有人可能会发现比这更有说服力的东西,但这应该能达到你想要的效果。您需要以下导入:
Imports System.Reflection
如果使用属性访问变量,则可以使用反射按名称抓取它们:
'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