我正在尝试通过Access 2013将数据从SQL查询返回到我的VB表单中,我的代码如下所示。
Private Sub frm_8_IncidentResponseSelect_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As New DataTable
Dim query As String = "select ([response ID] &' '&[response date]) As responsedetails from response where [incident id] = " & txt_incidentid.Text & " "
Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyDatabase"
Using command As New OleDbCommand(query, connection)
Using adapter As New OleDbDataAdapter(command)
connection.Open()
adapter.Fill(dt)
connection.Close()
End Using
End Using
End Using
For Each Data As DataRow In dt.Rows
If dt.Rows.Count > 0 Then
cb_responseid.DataSource = dt
cb_responseid.DisplayMember = "[responsedetails]"
cb_responseid.ValueMember = "[response id]
End If
Next
End Sub
我遇到了两个错误,但首先是
VB正在返回以下错误消息
'无法绑定到新的显示成员' 并突出显示以下代码行 cb_responseid.ValueMember =“[响应ID]
但是,combox框中的任何项目都以System.Data.DataRowView
的形式返回有人可以告诉我代码出错的方式/原因吗?
答案 0 :(得分:1)
首先,您应该删除表格行上的循环,只需将DataTable设置为DataSource,然后删除用于DisplayMember
和ValueMember
属性的字符串周围的方括号
If dt.Rows.Count > 0 Then
cb_responseid.DataSource = dt
cb_responseid.DisplayMember = "responsedetails"
cb_responseid.ValueMember = "responseid"
End If
然后,您需要更改查询以返回[response id]
字段,因为(在将其重命名为没有空格的内容之后)。您的代码使用该字段组成一个名为responsedetails
的新字段,因此它不再可用作ValueMember
Dim query As String = "select [response id] as responseid, " & _
" ([response ID] &' '&[response date]) As responsedetails " & _
" from response where [incident id] = " & txt_incidentid.Text & " "
说,记住构建命令文本连接字符串是你可以用数据库编程做的最糟糕的事情。您应该学习如何使用参数化查询
我要改变的另一件事是使用带有空格的这些字段。他们是一个非常嘈杂的分心,造成比他们解决更多的麻烦。