【问题标题】:Trouble with checking type of user control检查用户控件类型的问题
【发布时间】:2019-03-27 21:37:02
【问题描述】:

我有一组要绑定到数据源的组合框。

将有超过 200 个组合框都绑定到同一个源,因此我正在考虑使用循环来遍历表单上的所有控件,找到合适的控件并进行绑定。

这是我目前的代码:

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 之外没有其他代码来填充 DataSet。 组合框位于标签页中,因此表单上还有其他控件。

目前我收到错误消息:

'System.Windows.Forms.UserControl' 类型的表达式永远不能是 输入“System.Windows.Forms.ComboBox”。

任何帮助解决这个问题。

【问题讨论】:

  • UserControl 用于使用 Visual Studio 设计器设计一组控件,而 Control 是所有控件的基类。如果您只想迭代表单上的所有复选框并且它们不在用户控件中,您的代码应该是:For Each uxControl As Control In Me.Controls
  • 或者更好的是,删除If TypeOf (uxControl) Is ComboBox Then 语句并将循环更改为:For Each cbControl As ComboBox In Me.Controls.OfType(Of ComboBox)

标签: vb.net combobox user-controls controls


【解决方案1】:

改变

For Each uxControl As UserControl In Me.Controls

For Each uxControl As Control In Me.Controls

UserControl 提供了一个空控件,可用于创建其他控件。

就像在 cmets 中已经提到的那样,您也可以使用一些 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

【讨论】:

  • 嗨,MatSnow。感谢您更改控件的语法。还要向上面的 Visual Vincent 大喊一声,让 LINQ 代码整理出它工作得很好的代码。现在我需要做的就是在 3 个标签页上创建 150 个 ComboBox,以反映我们大楼 3 层楼的布局。
猜你喜欢
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多