Hi, I have put together (in a laborious fashion) code that controls multiple comboboxes and their selectedIndexChanged events.
I am using the selectedIndexChanged event to catch when the .text of the comboBox changes, and also to remember the .selectedIndex, so that when the box drops down again, it returns selected at the same position.
I have multiple iterations of the 2 subs at the bottom of the post for cmbA, cmbB, cmbC etc, and (in the spirit of "if you type it more than once, it can be coded better") I would like to redesign my code so that I can handle all the comboboxes in one sub, ie :
########
private sub comboBox_DropDown( blah ) handles cmbA.Dropdown
private sub comboBox_DropDown( blah ) handles cmbB.Dropdown
private sub comboBox_DropDown( blah ) handles cmbC.Dropdown
and
private sub comboBox_SelectedIndexChanged ( blah ) handles cmbA.SelectedIndexChanged, cmbB.SelectedIndexChanged, cmbC.SelectedIndexChanged
#########
BUT..... I'm stumped as to how I can get the control names and unique variable names that describe the selectedIndex & text values to be passed to the dropdown event and be handles.
My code that I'm starting from is below, I (think) I need to keep the multiple dropdown events as each one has a unique SQL statement, but if I can at least get rid of the repeated selectedIndexChanged code it would be a start.
#########
Private Sub cmbA_DropDown(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbA.DropDown
cmbA.SelectedIndex = -1
cmbA.Items.Clear()
Try
Dim query As String = "select something from a dbase"
Dim connection As New MySqlConnection(connStr)
Dim cmd As New MySqlCommand(query, connection)
connection.Open()
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader()
While reader.Read()
cmbA.Items.Add(reader.GetValue(0))
End While
reader.Close()
connection.Close()
Catch ex As MySqlException
Console.WriteLine(ex.Message)
MessageBox.Show("Database error # " & ex.Number & ": " & ex.Message, ex.GetType.ToString)
End Try
If cmbA_SelectedIndex <> -1 Then
Try
cmbA.SelectedIndex = cmbA_SelectedIndex
Catch ex As Exception
cmbA.SelectedIndex = -1
End Try
End If
End Sub
Private Sub cmbA_selectedindexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbA.SelectedIndexChanged
cmbA_Value = cmbA.Text
cmbA_SelectedIndex = cmbA.SelectedIndex
end sub
#########


Reply With Quote

