我正在为我的计算课程做一个项目。请帮忙。
我希望能够采用像这样的基本代码......
lblSectionsAttempted.ForeColor = Color.Green
基本上把它变成了这个......但是这不起作用:
lblSectionsAttempted(TempInc).ForeColor = Color.Green
TempInc是一个变量,每次循环完成后会增加1。
我有14' lblSectionAttempted'我表格上的标签。我希望能够根据变量TempInc的值来改变每个标签的前色......例如:
所以当TempInc = 1时,我希望lblSectionsAttempted1.ForeColor改变
然后当TempInc = 2时,我想lblSectionsAttempted2.ForeColor改变
If TempInc = 1 Then
lblSectionsAttempted1.ForeColor = Color.Green
Else if TempInc = 2 Then
lblSectionsAttempted2.ForeColor = Color.Green
等。等。
然而,有很多if语句并不理想。请有人告诉我如何重写这行代码,使变量的值影响标签的更改。
lblSectionsAttempted(TempInc).ForeColor = Color.Green
答案 0 :(得分:0)
假设您的标签名为lblSectionsAttempted1到lblSectionsAttempted14,那么我将创建一个控件数组并使用它来循环并更新标签的前景色:
' Create the control array
Dim oLabelArray(13) As Label
oLabelArray(0) = Me.lblSectionAttempted1
oLabelArray(1) = Me.lblSectionAttempted2
oLabelArray(2) = Me.lblSectionAttempted3
oLabelArray(3) = Me.lblSectionAttempted4
oLabelArray(4) = Me.lblSectionAttempted5
oLabelArray(5) = Me.lblSectionAttempted6
oLabelArray(6) = Me.lblSectionAttempted7
oLabelArray(7) = Me.lblSectionAttempted8
oLabelArray(8) = Me.lblSectionAttempted9
oLabelArray(9) = Me.lblSectionAttempted10
oLabelArray(10) = Me.lblSectionAttempted11
oLabelArray(11) = Me.lblSectionAttempted12
oLabelArray(12) = Me.lblSectionAttempted13
oLabelArray(13) = Me.lblSectionAttempted14
' Now if you are updating all controls to the color green you can do this:
For TempInc As Int32 = 0 To oLabelArray.Count - 1
oLabelArray(TempInc).ForeColor = Color.Green
Next
答案 1 :(得分:0)
您可以使用Controls.Find():
Dim matches() As Control = Me.Controls.Find("lblSectionsAttempted" & TempInc, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is Label Then
Dim lbl As Label = DirectCast(matches(0), Label)
lbl.ForeColor = Color.Green
End If