我试图枚举满足特定条件的表单中的所有控件,如代码beelow
Public Enum MethodSeachEnum
StartsWith = 1
EndsWith = 2
Contains = 3
End Enum
Public Function GetAllControls(Control As Control, Key As String, MethodSeach As MethodSeachEnum, ControlType As Type, Optional UseTag As Boolean = True) As IEnumerable(Of Control)
Dim controls = Control.Controls.Cast(Of Control)()
Return (controls.SelectMany(Function(ctrl) GetAllControls(ctrl, Metodo)).Concat(controls).Where(Function(c)
Select Case MethodSeach
Case MetodoSeachEnum.EndsWith
If (UseTag) Then
Return c.Tag.ToString.ToUpper.EndsWith(Key.ToUpper) And c.GetType() Is ControlType
Else
Return c.Name.ToUpper.EndsWith(Key.ToUpper) And c.GetType() Is ControlType
End If
Case MetodoSeachEnum.StartsWith
If (UseTag) Then
Return c.Tag.ToString.ToUpper.StartsWith(Key.ToUpper) And c.GetType() Is ControlType
Else
Return c.Name.ToUpper.StartsWith(Key.ToUpper) And c.GetType() Is ControlType
End If
Case MetodoSeachEnum.Contains
If (UseTag) Then
Return c.Tag.ToString.ToUpper.Contains(Key.ToUpper) And c.GetType() Is ControlType
Else
Return c.Name.ToUpper.Contains(Key.ToUpper) And c.GetType() Is ControlType
End If
Case Else
Return False
End Select
End Function))
End Function
在我的表单中有一个GroupBox,里面有一些TextBox。这些TextBox不会被退回,我也不明白为什么......
这是我如何调用此函数
Dim ctrls = GetAllControls(FormTagliente, "txtQuote", MetodoSeachEnum.StartsWith, GetType(TextBox), False)
For Each txt As TextBox In ctrls
...
Next
答案 0 :(得分:1)
恕我直言的信息太少,无法回答你的问题“为什么这对你的具体情况不起作用” 你的代码中也缺少带有两个参数的GetAllControls,也许问题在于 无论如何,我玩了一些你的代码(但没有测试它,所以它更像是POC),这就是我得到的:
$oid
我们的想法是将“构造标准逻辑”与实际的“循环,搜索,产生”分开,使用通用约束强制targetType为Control(并直接使用“good”返回类型) 。我也发现使用Enum SearchMethod
StartsWith = 1
EndsWith = 2
Contains = 3
End Enum
Function GetAllControls(Of T As Control)(ctrl As Control, key As String, method As SearchMethod, Optional useTag As Boolean = True) As IEnumerable(Of T)
' TODO validate args
Dim upperKey = key.ToUpper
Dim searchPredicates() As Func(Of String, Boolean) = {
Function(src, tgt) src.StartsWith(upperKey),
Function(src, tgt) src.EndsWith(upperKey),
Function(src, tgt) src.Contains(upperKey)
}
Dim ctrlSelector As Func(Of Control, String) = If(useTag, Function(c) c.Tag.ToString.ToUpper, Function(c) c.Name.ToUpper)
Return GetAllControlsIterator(Of T)(ctrl, ctrlSelector, searchPredicates(CInt(method) - 1))
End Function
Private Iterator Function GetAllControlsIterator(Of T As Control)(ctrl As Control, ctrlSelector As Func(Of Control, String), searchPredicate As Func(Of String, Boolean)) As IEnumerable(Of T)
For Each child In ctrl.Controls
If searchPredicate(ctrlSelector(child)) AndAlso TypeOf child Is T Then Yield DirectCast(child, T)
For Each grandChild In GetAllControlsIterator(Of T)(child, ctrlSelector, searchPredicate)
Yield DirectCast(grandChild, T)
Next
Next
End Function
块更简单,但更个性化
也许这可以帮助你解决问题?