2016-06-29 20 views
1

我有20個標籤,與像lbl_A1lbl_A2lbl_A3lbl_A4lbl_B1lbl_B2lbl_B3lbl_B4 ......直到lbl_E4名。每個標籤forecolor應根據數據庫中的值0 = red, 1 = yellow, 2 = green進行更改。比較標籤的名稱的最後2串前2字符串變量

'I arrayed all the values of it, each item contains its specific value 
Dim lightFunctions = New Integer() {a1_LightFunction, b1_LightFunction, c1_LightFunction, d1_LightFunction, e1_LightFunction _ 
      , a2_LightFunction, b2_LightFunction, c2_LightFunction, d2_LightFunction, e2_LightFunction _ 
      , a3_LightFunction, b3_LightFunction, c3_LightFunction, d3_LightFunction, e3_LightFunction _ 
      , a4_LightFunction, b4_LightFunction, c4_LightFunction, d4_LightFunction, e4_LightFunction} 

    'Loop through each item of array and get the value 
    For Each lightFunctionsValue As Integer In lightFunctions 

     'Loop through each label in my form 
     For Each c As Label In Me.Controls.OfType(Of Label)() 
      'This is my problem, I don't know how to make this that if it detects that for example the label's name ends with A1 then it should get the value of a1_LightFunction the if it is 0 it should be red 
      If c.Name.EndsWith("") and lightFunctionsValue = 0 Then c.ForeColor = color.red 
      If c.Name.EndsWith("") and lightFunctionsValue = 1 Then c.ForeColor = color.yellow 
      If c.Name.EndsWith("") and lightFunctionsValue = 2 Then c.ForeColor = color.green 
     Next 
    Next 

我相信,如果我這樣做,我能避免,如果這麼多的情況是這樣

If a1_LightFunction = 0 Then 
     lbl_A1.ForeColor = Color.Red 
    End If 
    If b1_LightFunction = 0 Then 
     lbl_B1.ForeColor = Color.Red 
    End If 
    If c1_LightFunction = 0 Then 
     lbl_C1.ForeColor = Color.Red 
    End If 
    If d1_LightFunction = 0 Then 
     lbl_D1.ForeColor = Color.Red 
    End If 
    If e1_LightFunction = 0 Then 
     lbl_E1.ForeColor = Color.Red 
    End If 

    And so on and so forth until it reaches .... 

    If e4_LightFunction = 2 Then 
     lbl_E4.ForeColor = Color.Green 
    End If 
+0

爲什麼不寫一個小類將標籤鏈接到一個值。當你改變對象的值時,讓它設置顏色。 – Plutonix

+0

對不起,這可能是一個基本問題。創建一個「將類標籤鏈接到值的小類」意味着我不需要將20個標籤拖放到GUI上? –

+0

@Plutonix你的答案已被刪除先生,我仍然在嘗試它。 :( –

回答

1

所有你可能需要的是一點點抽象和辦法標籤用某種鏈接關鍵:

Private lblCol As Dictionary(Of String, Label) 
... 
Dim lbls As Label() = {Label2, Label3, Label4, Label5} 
Dim keys As String() = {"lbl_a1", "lbl_c1", "lbl_b4", "lbl_d3"} 

lblCol = New Dictionary(Of String, Label) 
For n As Int32 = 0 To keys.Count - 1 
    lblCol.Add(keys(n), lbls(n)) 
Next 

然後一個通用的更新:

Private Sub UpdateLabel(lbl As Label, n As Int32) 
    Select Case n 
     Case 0 
      lbl.BackColor = Color.Red 
     Case 1 
      lbl.BackColor = Color.Yellow 
     Case 2 
      lbl.BackColor = Color.Green 
    End Select 
End Sub 

環通所有的人:

For Each kvp In lblCol 
    UpdateLabel(kvp.Value, RNG.Next(0, 3)) 
Next 

找到他們使用的關鍵,這在你原來的方法是名稱:

Dim find = "lbl_a1" 
UpdateLabel(lblCol(find), RNG.Next(0, 3)) 

的關鍵需求被什麼東西從DB簡單,讓您可以設置鏈接/地圖並簡化查找正確的控件。

RNG是一個Random對象,您將使用DB值。

+0

非常感謝你,儘管這裏字典是*鍵*。 –