2017-04-10 112 views
1

有沒有辦法改變10個標籤的顏色和一個命令?有沒有辦法改變'n'標籤的顏色和一個命令?

例如,而不是:

Label1.ForeColor = Color.Black 
Label2.ForeColor = Color.Black 
Label3.ForeColor = Color.Black 
Label4.ForeColor = Color.Black 
Label5.ForeColor = Color.Black 
Label6.ForeColor = Color.Black 
Label7.ForeColor = Color.Black 

我想只使用一個命令來更改ForeColor。例如,而不是Label1它將是LabelX

回答

5

您可以遍歷所有類型爲label的控件。 這應該會訣竅。

'For each control in the form 
For Each ctrl As Control In Me.Controls 
    'If its of type label 
    If TypeOf ctrl Is Label Then 
     'Change the color 
     ctrl.ForeColor = Color.Black 
    End If 
Next 

主編文森特一樣所以建議我們不需要之前聲明的點擊率。

由於錯誤提示這裏是一個更短的選項:

For Each ctr In Me.Controls.OfType(Of Label) 
    ctr.ForeColor = Color.Black 
Next 
1
For i As Integer = 1 To 7 
    Dim xL As Label = DirectCast(Controls("Label" & i.ToString), Label) 
    xL.ForeColor = Color.Black 
Next 
1

你可以做一個循環,從1到X,並通過與X串聯詞Label按名稱獲取每個標籤。

Private Sub SetLabelRangeColor(ByVal [End] As Integer, ByVal Color As Color) 
    SetLabelRangeColor(1, [End], Color) 
End Sub 

Private Sub SetLabelRangeColor(ByVal Start As Integer, ByVal [End] As Integer, ByVal Color As Color) 
    If Start > [End] Then Throw New ArgumentOutOfRangeException 

    For x = Start To [End] 
     Dim TargetLabel As Label = TryCast(Me.Controls("Label" & x), Label) 
     If TargetLabel IsNot Nothing Then 
      TargetLabel.ForeColor = Color 
     End If 
    Next 
End Sub 

用法:

SetLabelRangeColor(<end label no.>, <color>) 
'Or: 
SetLabelRangeColor(<start label no.>, <end label no.>, <color>) 

使用示例:

'Label 1-6: 
SetLabelRangeColor(6, Color.Red) 

'Label 4-9: 
SetLabelRangeColor(4, 9, Color.Red) 
3

這是一個遞歸溶液將解決被置於容器內Label控制諸如GroupBoxPanel

我會嘗試向您展示差異來解釋爲什麼可能需要遞歸方法。我使用Color.Red來說明不同之處。您可以將代碼更改爲Color.Black

下面的代碼將在ForeColor屬性設置爲已放置在窗體上Color.RedLabel控制:

For Each lbl As Label In Me.Controls.OfType(Of Label)() 
    lbl.ForeColor = Color.Red 
Next 

這是它的樣子:

enter image description here

你可以在這裏看到只有Label4被設置。

下面的代碼將設置所有Label控制:

Private Sub SetAllLabelsForeColor(ByVal parent As Control) 

    For Each c As Control In parent.Controls 
     If TypeOf (c) Is Label Then 
      c.ForeColor = Color.Red 
     Else 
      If c.HasChildren Then 
       SetAllLabelsForeColor(c) 
      End If 
     End If 
    Next 

End Sub 

然後,您可以用下面的代碼調用此:

SetAllLabelsForeColor(Me) 

這是結果的截圖:

enter image description here

相關問題