将标签名称的最后 2 个字符串与变量的前 2 个字符串进行比较

Compare the last 2 strings of the name of the label to the first 2 string of the variable

我有 20 个标签,名称如 lbl_A1lbl_A2lbl_A3lbl_A4lbl_B1lbl_B2lbl_B3lbl_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 条件

    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

您可能需要的只是一点抽象和一种使用某种键 link 标签的方法:

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

密钥需要是来自数据库的简单内容,以允许您设置 link/map 并使找到正确的控件变得简单。

RNG 是一个 Random 对象,您将使用 DB 值。