Search code examples
vb.netcomboboxuser-controlscontrols

Trouble with checking type of user control


I have a group of ComboBoxs that I am looking to bind to a datasource.

There are going to be upwards of 200 ComboBoxs all being bound to the same source and so I am looking at doing this using a loop to go through all the controls on the form, find appropriate controls and do binding.

Here is the code I have so far:

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

There currently is no other code apart from the SQL to fill the DataSet. The ComboBoxs are in a tab page so there are other controls on the form.

At the moment I am getting the error message :

Expression of type 'System.Windows.Forms.UserControl' can never be of type 'System.Windows.Forms.ComboBox'.

Any help in resolving this.


Solution

  • Change

    For Each uxControl As UserControl In Me.Controls
    

    to

    For Each uxControl As Control In Me.Controls
    

    A UserControl provides an empty control that can be used to create other controls.

    Like already mentioned in comments you could also use some LINQ to get rid of the line
    If TypeOf (uxControl) Is ComboBox Then and change the For Each-loop as follows:

    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