我试图循环我的窗体VB.net应用程序上的所有组合框。
我以为这会起作用
Array.ForEach(Me.Controls.OfType(Of ComboBox).Items.Add(DataGridView1.Columns(i).Name)))
但是我不能指那些似乎不知道它是那时的组合
我正在尝试获取所有组合框名称的列表,因此我希望在循环中使用该名称列表来添加项目并读取所选索引,但我的名称列表始终为空白。我正在使用以下代码只是尝试将列表发送到一个消息框,看看它是否抓取任何名称。
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim allComboBoxValues As String = ""
Dim c As Control
Dim childc As Control
For Each c In Me.Controls
For Each childc In c.Controls
If TypeOf childc Is ComboBox Then
allComboBoxValues &= CType(childc, ComboBox).Text & ","
End If
Next
Next
MsgBox(allComboBoxValues)
If allComboBoxValues <> "" Then
MsgBox(allComboBoxValues)
End If
End Sub
波纹管function
可用于检索某种类型的所有儿童Controls
。
Private Function GetAll(Control As Control, Type As Type) As IEnumerable(Of Control)
Dim Controls = Control.Controls.Cast(Of Control)()
Return Controls.SelectMany(Function(x) GetAll(x, Type)).Concat(Controls).Where(Function(y) y.GetType = Type)
End Function
用法:
GetAll(Me, GetType(Combobox))
满足您的需求:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Values As String = String.Empty
For Each ComboBox As ComboBox In GetAll(Me, GetType(ComboBox))
Values &= ComboBox.Text & ","
Next
MsgBox(Values)
End Sub
(Qazxswpoi)
我使用这种扩展方法。它使用非常干净的泛型。正如评论中所提到的,递归是必要的。
Function retrieved from this answer and converted to vb.net
在您的方案中使用:
Public Module ExtensionMethods
<Extension()>
Public Function ChildControls(Of T As Control)(ByVal parent As Control) As IEnumerable(Of T)
Dim result As New List(Of T)
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is T Then result.Add(CType(ctrl, T))
result.AddRange(ctrl.ChildControls(Of T)())
Next
Return result
End Function
End Module