如何遍历容器中的所有对象?

时间:2013-10-25 13:56:50

标签: arrays vb.net object collections

如果我有一个标签数量未知的面板,我该如何浏览所有标签并更改其中的.text值?我试过这样的事情:

for each x as label in mypanel
   x.text = "whatever"
next

但是我得到一个错误,即mypanel不是一个集合。

标签是mypanel的子女。

5 个答案:

答案 0 :(得分:2)

获胜表单试试:

for each x as Control in mypanel.Controls
   if TypeOf x Is Label Then
     CType(x, Label).text = "whatever"
   end if
next

答案 1 :(得分:0)

取决于Panel这是什么类型。 WinFormsWPF?错误是正确的,Panel不是集合。这只是一个对象。但其中一个属性可能是一个集合。

对于WinForms,

mypanel.Controls,对于WPF,则为mypanel.Children。如果层次结构多于直接子项,那么您可能需要进一步递归到该层次结构中。

答案 2 :(得分:0)

For Each lbl As Label in myPanel.Controls
     lbl.Text = "whatever"
Next

假设myPanel上的所有内容都是标签。如果还有其他控件,则必须测试它们是否为标签:

For Each ctl as Control in myPanel.Controls
     If Ctl.GetType = Label.GetType Then
        CType(ctl, Label).text = "whatever"
     End if
Next

答案 3 :(得分:0)

遍历面板中的所有控件,然后确定每个控件是否为Label,如下所示:

For Each theControl As Control In myPanel.Controls
    If TypeOf theControl Is Label Then
        ' Change the text here
        TryCast(theControl, Label).Text = "whatever"
    End If
Next

更新:

要考虑面板中的子控件,请执行以下操作:

Dim listOfLabels As New List(Of Control)

Public Sub GetAllLabelsIn(container As Control)
    For Each theControl As Control In container.Controls
        If TypeOf theControl Is Label Then    
            listOfLabels.Add(theControl)

            If theControl.Controls.Count > 0 Then
                GetAllLabelsIn(theControl)
            End If
        End If
    Next
End Sub

现在你可以这样称呼它:

listOfLabels = new List(Of Control)

GetAllLabelsIn(myPanel)

For Each theControl As Control In listOfLabels
    If TypeOf theControl Is Label Then
        ' Change the text here
        TryCast(theControl, Label).Text = "whatever"
    End If
Next

答案 4 :(得分:-1)

您首先只能选择Label。这也会在容器内的容器内返回标签......

' Inside a module
<Extension()> _
Public Function ChildControls(Of T As Control)(ByVal parent As Control) As List(Of T)
    Dim result As New ArrayList()
    For Each ctrl As Control In parent.Controls
        If TypeOf ctrl Is T Then result.Add(ctrl)
        result.AddRange(ChildControls(Of T)(ctrl))
    Next
    Return result.ToArray().Select(Of T)(Function(arg1) CType(arg1, T)).ToList()
End Function

用法:

For Each myLabel as Label in myPanel.ChildControls(Of Label)
    myLabel.Text = "I'm a label!"
Next