我有20个标签,名称如lbl_A1
, lbl_A2
, lbl_A3
, lbl_A4
, lbl_B1
, lbl_B2
, lbl_B3
, lbl_B4
…直到lbl_E4
。每个标签的前颜色应根据数据库0 = red, 1 = yellow, 2 = green
中的值进行更改。
'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
您可能需要的只是一些抽象和一种使用某种键连接标签的方法:
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值。