I trust you’re all well. I would like to know what I’m doing wrong and how to fix it. My intent with the code below is the query my MySQL database and display one column of the table inside a ComboBox. Then, when that value in the ComboBox is selected, I want all the records associated to be populated into other controls on my form (I’ll create a separate question for this part).
Right now, the query is working but the ComboBox isn’t being populated. What am I doing wrong? Please help, thanks.
HERE’S MY CODE:
Private Sub RetrieveMySQLdata()
Try
Dim dbConn As New MySqlConnection
Dim dbQuery As String = ""
Dim dbCmd As New MySqlCommand
Dim dbAdapter As New MySqlDataAdapter
Dim dbTable As New DataTable
If dbConn.State = ConnectionState.Closed Then
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
dbConn.Open()
End If
dbQuery = "SELECT *" & _
"FROM cc_master INNER JOIN customer ON customer.accountNumber = cc_master.customer_accountNumber " & _
"WHERE customer.accountNumber = '" & TextBoxAccount.Text & "'"
With dbCmd
.CommandText = dbQuery
.Connection = dbConn
End With
With dbAdapter
.SelectCommand = dbCmd
.Fill(dbtable)
End With
Dim i As Integer
For i = 0 To dbTable.Rows.Count - 1
ComboBoxCard.ValueMember = "ccNumber"
Next
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
End Sub
Where are you trying to populate the
ComboBox? The only interaction I see is here:Which I’m guessing isn’t doing what you think it’s doing. For one thing, you’re setting
ValueMemberto the same value multiple times in a loop. Nothing in the statement changes with each iteration of the loop, so why loop it?More specifically,
ValueMemberisn’t actually any kind of displayed value. It’s used to indicate which field in the bound data should contain the value. This is used when you provide aDataSourcefor the control, which you’re missing.I’ll assume the
DataSourceshould bedbTable, so you’re probably looking to do something like this:I don’t remember if you need to explicitly call
.DataBind()on the control after these statements, but the example I linked to doesn’t do it so I’ll leave it out.Essentially what you’re trying to do in your code is loop through the results and add them to the
ComboBox. You don’t need to do this. TheComboBoxis capable of doing this internally if you just point itsDataSourceto the set of data being used and tell it which fields it needs to use on that set. This is called data binding.