Two ComboBoxes with Same BindingSource Won't Move Together
I have a dialog that has two ComboBox controls that are bound to the same BindingSource object (from a DataTable). However, when I select an item in one of the ComboBoxes, it seems to be confused about which item it's supposed to select in the other ComboBox.
Here's the basic code I have in place:
Private UserBinding As BindingSource Private Loading As Boolean Private SelectedUserID As Integer Private Sub dlgUserData_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Loading = True Dim UserList As DataTable = GetActiveUsers() UserBinding = New BindingSource UserBinding.DataSource = UserList With Me.cboUsers .DataSource = UserBinding .ValueMember = "UserNumber" .DisplayMember = "UserName" .SelectedIndex = -1 End With With Me.cboUID .DataSource = UserBinding .ValueMember = "UserNumber" .DisplayMember = "UID" .SelectedIndex = -1 End With End Sub Private Sub dlgUserData_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown Loading = False Me.BringToFront() End Sub
UserNumber is an Integer value in the
UserList DataTable. The
UID are String values. I've been testing with a known database record that has a specific
UID value. However, when I select that
UID in the
cboUID ComboBox, a different
UserName value than is expected shows up in the
I put the following code in the
SelectedIndexChanged event handler for each of the ComboBoxes so I could put a breakpoint on it and see what it's doing:
Private Sub cboUsers_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboUsers.SelectedIndexChanged If Not Loading Then SelectedUserID = Convert.ToInt32(DirectCast(Me.cboUsers.Items(Me.cboUsers.SelectedIndex), DataRowView)("UserNumber").ToString()) End If End Sub Private Sub cboUID_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboUID.SelectedIndexChanged If Not Loading Then SelectedUserID = Convert.ToInt32(DirectCast(Me.cboUID.Items(Me.cboUID.SelectedIndex), DataRowView)("UserNumber").ToString()) End If End Sub
Unfortunately, the only thing this code does is prove the problem exists. When one ComboBox value changes, the other ComboBox does change, but it changes to the wrong value. I've tried creating separate BindingSources and trying to manually keep them in sync, but that seems to give me even more random results.
Just for reference, my testing is to select from
cboUID the item with a value of
975. When I do this,
cboUsers displays the item with a value of
495 (verified with my code for the
SelectedIndexChanged event). I know I'm probably just overlooking something here, but I can't figure out what that is.
Oh, and in case it matters, I'm using VS2015 CE on Windows 7 Pro. Thanks for your help.