我想列出以“btn”开头的所有按钮名称,但这些按钮位于不同的面板中。我有这个在我的脑海vb.net查找以表单中指定字符串开头的控件
dim obj() as object in frmForm.Controls.Find(True,"btn*")
但我认为这可能是错的..
我想列出以“btn”开头的所有按钮名称,但这些按钮位于不同的面板中。我有这个在我的脑海vb.net查找以表单中指定字符串开头的控件
dim obj() as object in frmForm.Controls.Find(True,"btn*")
但我认为这可能是错的..
我做控件的类型类似的东西,但它可以很容易地修改名称。试试下面的代码:
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类继承的任何东西),则需要将该对象作为适当的控件。所以,如果.NAME只有Button类,并在控制类是不存在的,我会做以下这个工作:
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
首先,第一个参数是名字,第二个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)
我会尝试测试它。谢谢! – illumi
你试过编译这个吗? http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.find(v=vs.110).aspx –
是的......但是当我的按钮名称是“btnSave”它的回报没有任何。 – illumi