我相信你一切顺利。我想知道我做错了什么以及如何解决它。我对下面代码的意图是查询我的MySQL数据库并在ComboBox中显示表的一列。然后,当选择ComboBox中的值时,我希望关联的所有记录都填充到表单上的其他控件中(我将为此部分创建一个单独的问题)。
现在,查询正在运行,但未填充ComboBox。我究竟做错了什么?请帮助,谢谢。
这是我的代码:
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
答案 0 :(得分:2)
你想在哪里填充ComboBox
?我看到的唯一互动就是:
For i = 0 To dbTable.Rows.Count - 1
ComboBoxCard.ValueMember = "ccNumber"
Next
我猜测的并不是你认为它在做什么。首先,您在循环中多次将ValueMember
设置为相同的值。语句中的任何内容都不会随着循环的每次迭代而改变,那么为什么要循环呢?
更具体地说,ValueMember
实际上不是任何类型的显示值。 It's used to indicate which field in the bound data should contain the value。当您为控件提供DataSource
时,会使用此选项。
我假设DataSource
应该是dbTable
,所以你可能希望做这样的事情:
ComboBoxCard.DataSource = dbTable
ComboBoxCard.ValueMember = "ccNumber"
ComboBoxCard.DisplayMember = "Some Other Field in the database"
我不记得你是否需要在这些语句之后在控件上显式调用.DataBind()
,但是我链接的示例没有这样做,所以我会把它留下来。
您在代码中尝试执行的操作基本上是遍历结果并将其添加到ComboBox
。你不需要这样做。 ComboBox
能够在内部执行此操作,只需将其DataSource
指向正在使用的数据集,并告诉它需要在该集合上使用哪些字段。这称为data binding。
答案 1 :(得分:1)
看起来您没有为ComboBox对象设置DataSource
。而不是这段代码:
Dim i As Integer
For i = 0 To dbTable.Rows.Count - 1
ComboBoxCard.ValueMember = "ccNumber"
Next
使用类似代码:
ComboBoxCard.DataSource = dbTable
ComboBoxCard.ValueMember = "ccNumber"
ComboBoxCard.DisplayMember = "(some other column if you want)"