vb.netdatasourcetableadaptertoolstripcombobox

Filling a TableAdapter from Bound ToolStripComboBox


I am trying to fill a TableAdapter based on a selection from a ToolStripComboBox. First I want to fill the ToolStipComboBox by binding it to a datasource. Then once it is filled, I want to fill the TableAdapter.

This is my code:

Private Sub ToolStripComboBox_MessageType_Click(sender As Object, e As EventArgs) Handles ToolStripComboBox_MessageType.Click
    Me.ToolStripComboBox_MessageType.ComboBox.DataSource = DataSet_UToolDb.XML_MESSAGE_TYPE
    Me.ToolStripComboBox_MessageType.ComboBox.DisplayMember = "MessageType"
    Me.ToolStripComboBox_MessageType.ComboBox.ValueMember = "MTId"
End Sub

Private Sub ToolStripComboBox_MessageType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ToolStripComboBox_MessageType.SelectedIndexChanged
    Me.TableAdapter_XML_MESSAGE_STRUCTURE.Fill(DataSet_UToolDb.XML_MESSAGE_STRUCTURE, Me.ToolStripComboBox_MessageType.ComboBox.SelectedValue)
End Sub

For some reason (if I step through my code) the code jumps from the where the datasource is set, to where the TableAdapter is filled. This is causing an exception as the TableAdapter's select query is looking for a value based on the value that was selected from the ToolStipComboBox.


Solution

  • I suspect your code is jumping to where the TableAdapter is filled because by setting the DataSource of the ComboBox you're causing the SelectedIndexChanged event to be fired.

    So, you need to tell the SelectedIndexChanged handler to return should the ToolStripComboBox not be populated yet, which you could do by setting a Boolean flag when the ToolStripComboBox has been populated. For example:

    Dim m_ToolStripComboBoxPopulated As Boolean
    
    Private Sub ToolStripComboBox_MessageType_Click(sender As Object, e As EventArgs) Handles ToolStripComboBox_MessageType.Click
        Me.m_ToolStripComboBoxPopulated = False
        Me.ToolStripComboBox_MessageType.ComboBox.DataSource = DataSet_UToolDb.XML_MESSAGE_TYPE
        Me.ToolStripComboBox_MessageType.ComboBox.DisplayMember = "MessageType"
        Me.ToolStripComboBox_MessageType.ComboBox.ValueMember = "MTId"
        ' Indicate ToolStripComboBox has been populated
        Me.m_ToolStripComboBoxPopulated = True
    End Sub
    
    Private Sub ToolStripComboBox_MessageType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ToolStripComboBox_MessageType.SelectedIndexChanged
        If (Me.m_ToolStripComboBoxPopulated = False) Then
            Return
        End If
        Me.TableAdapter_XML_MESSAGE_STRUCTURE.Fill(DataSet_UToolDb.XML_MESSAGE_STRUCTURE, Me.ToolStripComboBox_MessageType.ComboBox.SelectedValue)
    End Sub