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

时间:2016-06-29 01:17:55

标签: vb.net loops labels

我有20个标签,其中包含lbl_A1lbl_A2lbl_A3lbl_A4lbl_B1lbl_B2,{{1}等名称},lbl_B3 ...直到lbl_B4。每个标签forecolor都应根据数据库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

1 个答案:

答案 0 :(得分:1)

您可能需要的只是一点抽象,并且可以通过某种键来标记标签:

SELECT CONVERT(varchar, CAST(987654321 AS money), 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)) RNG对象,您可以使用数据库值。