vb.net 查找窗体中以指定字符串开头的控件



我想列出以"btn"开头的所有按钮名称,但这些按钮位于不同的面板中。我心里有这个

dim obj() as object in frmForm.Controls.Find(True,"btn*")

但我认为这可能是错误的..

首先,第一个参数是名称,第二个参数是指示是否要递归搜索的bool

其次,没有内置的方法。我会使用你自己的方法,像这样:

Public Function FindControlStartsWith(root As Control, name As String, recursive As Boolean, comparison As StringComparison) As Control()
    If root Is Nothing Then
        Throw New ArgumentNullException("root")
    End If
    Dim controls = New List(Of Control)
    Dim stack = New Stack(Of Control)()
    stack.Push(root)
    While stack.Count > 0
        Dim c As Control = stack.Pop()
        If c.Name.StartsWith(name, comparison) Then
            controls.Add(c)
        End If
        If recursive Then
            For Each child As Control In root.Controls
                stack.Push(child)
            Next
        End If
    End While
    Return controls.ToArray()
End Function

以这种方式使用它:

Dim obj() As Control = FindControlStartsWith(Me, "BUT", True, StringComparison.OrdinalIgnoreCase)

我对控件类型做了类似的事情,但可以很容易地修改名称。尝试以下代码:

Private Sub findcontrols(ByVal root As Control)
    For Each cntrl As Control In root.Controls
        findcontrols(cntrl)
        If cntrl.name.startswith("btn") Then
            msgbox(cntrl.name)
        End If

End Sub

您可以通过为控制递归等内容添加参数来使这更加复杂。请记住,如果要使用它执行任何特定于控件类型的内容(即控件中不是从 Control 类继承的任何内容(,则需要将该对象作为适当的控件进行 CType。因此,如果 .name 仅在 Button 类中,而不存在在 Control 类中,则我必须执行以下操作才能正常工作:

msgbox(ctype(cntrl, Button).name)

我自己的个人版本看起来更像这样:

Private Sub clearcontrols(ByVal root As Control, ByVal ClearLists As Boolean, Optional ByVal ClearTabPages As Boolean = False)
    For Each cntrl As Control In root.Controls
        clearcontrols(cntrl, ClearLists, ClearTabPages)
        If TypeOf cntrl Is TextBox  Then
            CType(cntrl, TextBox).Clear()
        End If
        If TypeOf cntrl Is DataGridView Then
                CType(cntrl, DataGridView).Rows.Clear()
        End If
        If TypeOf cntrl Is ListBox   And ClearLists = True Then
                CType(cntrl, ListBox).Items.Clear()
        End If
        If TypeOf cntrl Is TabControl And ClearTabPages = True Then
            For Each tp As TabPage In CType(cntrl, TabControl).TabPages
                If DynTPList.Contains(tp.Name) Then
                    tp.Dispose()
                End If
            Next
        End If
    Next
End Sub

最新更新