2013-07-10 60 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