我有一个功能来清除组框内的文本框和组合框(DropDownList
)。虽然文本框正在清除,但我无法清除组合框。
Public Sub ClearGroupControls()
For Each groupboxControl As Control In Me.Controls
If TypeOf groupboxControl Is GroupBox Then
For Each control As Control In groupboxControl.Controls
' Clear controls
If TypeOf control Is TextBox Then
control.Text = ""
ElseIf TypeOf control Is ComboBox Then
'control.Text = String.Empty
'control.SelectedIndex = -1
control.Text = ""
End If
Next
End If
Next
End Sub
注意:.SelectedIndex = -1
会产生错误:
SelectedIndex不是System.Windows.Forms.Control
的成员
...考虑到control.Text,当控件是TextBox时,它似乎不一致。
答案 0 :(得分:2)
循环控件集合将返回一个没有SelectedIndex属性的通用控件 您需要将其强制转换为适当的类型
Public Sub ClearGroupControls()
For Each groupboxControl In Me.Controls.OfType(Of GroupBox)()
For Each control As Control In groupboxControl.Controls
' Clear controls
If TypeOf control Is TextBox Then
control.Text = ""
ElseIf TypeOf control Is ComboBox Then
Dim cbo = DirectCast(control, ComboBox)
cbo.SelectedIndex = -1
End If
Next
Next
End Sub
请注意,在外部循环中,您可以使用IEnumerable扩展,只需要Form中的Controls集合中的枚举器返回的GroupBox类型的控件。
您可以将内部循环更改为两个循环以利用OfType扩展,但如果它确实提供了更好的性能,则应该测量它(这在很大程度上取决于组框中存在的控件数量)
Public Sub ClearGroupControls()
For Each groupboxControl In Me.Controls.OfType(Of GroupBox)()
For Each txt In groupboxControl.Controls.OfType(Of TextBox)()
txt.Text = ""
Next
For Each cbo In groupboxControl.Controls.OfType(Of ComboBox)()
cbo.SelectedIndex = -1
Next
Next
End Sub