2013-07-10 61 views
1

我有一个很大的窗口,有一些小于200的控件/变量需要担心。他们中的许多人都是相似的,所以我想知道是不是每个人都可以单独调用每个人,我可以连接他们的名字。在VB中连接变量名称

我打一个比方:

我有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 

我知道,上面的代码不工作,但我想给你的就是我想做的基本思想。这看起来可行吗?

回答

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 

记住,拼接项目时, '+' 将在字符串和不是整数工作。您可能希望在连接时始终使用'&'

+0

完美地工作!谢谢! –

0

另一种方法是对每种类型的控件使用select-case块。事情是这样的:

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 
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