我正在为我的计算课程做一个项目。请真的帮忙。
我希望能够像这样编写一行基本代码...
lblSectionsAttempted.ForeColor = Color.Green
基本上把它变成这个...但这不起作用:
lblSectionsAttempted(TempInc).ForeColor = Color.Green
TempInc 是一个变量,每次循环完成时都会递增 1。
我的表单上有 14 个"lblSectionTryed"标签。我希望能够根据变量 TempInc 的值更改每个标签的前景色......所以例如:
所以当 TempInc = 1 时,我希望 lblSectionTryed1.ForeColor 改变
然后当 TempInc =2 时,我想 lblSectionTryed2.ForeColor 来更改
If TempInc = 1 Then
lblSectionsAttempted1.ForeColor = Color.Green
Else if TempInc = 2 Then
lblSectionsAttempted2.ForeColor = Color.Green
等等。
但是,有很多 if 语句并不理想。请有人告诉我如何重新编写这行代码以使变量的值影响更改的标签。
lblSectionsAttempted(TempInc).ForeColor = Color.Green
假设您的标签被命名为 lblSectionTryed1 到 lblSectionTryed14,那么我将创建一个控件数组并使用它来循环和更新标签的前色:
' 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
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