检查用户控件类型时遇到问题
Trouble with checking type of user control
我有一组要绑定到数据源的组合框。
将会有超过 200 个 ComboBox 都绑定到同一个源,因此我正在考虑使用循环遍历表单上的所有控件、找到合适的控件并进行绑定。
这是我目前的代码:
For Each uxControl As UserControl In Me.Controls
If TypeOf (uxControl) Is ComboBox Then
Dim tbControl As ComboBox = DirectCast(uxControl, ComboBox)
If tbControl.Name.StartsWith("cmbDesk") Then
tbControl.DataSource = myDS
tbControl.DisplayMember = "employee_id"
tbControl.ValueMember = "name"
End If
End If
Next
目前除了 SQL 之外没有其他代码来填充数据集。
ComboBox 位于标签页中,因此表单上还有其他控件。
目前我收到错误消息:
Expression of type 'System.Windows.Forms.UserControl' can never be of
type 'System.Windows.Forms.ComboBox'.
解决此问题的任何帮助。
改变
For Each uxControl As UserControl In Me.Controls
到
For Each uxControl As Control In Me.Controls
UserControl
提供了一个空控件,可用于创建其他控件。
就像评论中已经提到的那样,您也可以使用一些 LINQ 来摆脱行
If TypeOf (uxControl) Is ComboBox Then
并更改 For Each
-loop 如下:
For Each comboBox As ComboBox In Me.Controls.OfType(Of ComboBox)
If comboBox.Name.StartsWith("cmbDesk") Then
comboBox.DataSource = myDS
comboBox.DisplayMember = "employee_id"
comboBox.ValueMember = "name"
End If
Next
我有一组要绑定到数据源的组合框。
将会有超过 200 个 ComboBox 都绑定到同一个源,因此我正在考虑使用循环遍历表单上的所有控件、找到合适的控件并进行绑定。
这是我目前的代码:
For Each uxControl As UserControl In Me.Controls
If TypeOf (uxControl) Is ComboBox Then
Dim tbControl As ComboBox = DirectCast(uxControl, ComboBox)
If tbControl.Name.StartsWith("cmbDesk") Then
tbControl.DataSource = myDS
tbControl.DisplayMember = "employee_id"
tbControl.ValueMember = "name"
End If
End If
Next
目前除了 SQL 之外没有其他代码来填充数据集。 ComboBox 位于标签页中,因此表单上还有其他控件。
目前我收到错误消息:
Expression of type 'System.Windows.Forms.UserControl' can never be of type 'System.Windows.Forms.ComboBox'.
解决此问题的任何帮助。
改变
For Each uxControl As UserControl In Me.Controls
到
For Each uxControl As Control In Me.Controls
UserControl
提供了一个空控件,可用于创建其他控件。
就像评论中已经提到的那样,您也可以使用一些 LINQ 来摆脱行 If TypeOf (uxControl) Is ComboBox Then
并更改 For Each
-loop 如下:
For Each comboBox As ComboBox In Me.Controls.OfType(Of ComboBox)
If comboBox.Name.StartsWith("cmbDesk") Then
comboBox.DataSource = myDS
comboBox.DisplayMember = "employee_id"
comboBox.ValueMember = "name"
End If
Next