我是编程新手。我想要完成的是在VB.NET中填写9个文本框,使用组合框(CbbNaamfirma)读取访问表TblKlanten。我不能让这个为我的生活工作;我一直在寻找这个简单的东西6个小时。你们有人可以帮助我吗?我在SO.com上阅读了很多这样的线程,它们都不适合我。 我现在的代码:
Private Sub CbbNaamfirma_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CbbNaamfirma.SelectedIndexChanged
Dim Connection As New OleDb.OleDbConnection
Connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & Application.StartupPath & "\Database.accdb.'"
Try
Connection.Open()
Dim query As String
query = "SELECT Adres FROM TblKlanten WHERE [Naam firma] = ' " & CbbNaamfirma.Text & " ' "
Dim cmd As New OleDbCommand(query, Connection)
Dim Reader As OleDbDataReader = cmd.ExecuteReader
Reader = cmd.ExecuteReader
While Reader.Read
TxtAdresprev.Text = Reader.GetString("Adres")
End While
Connection.Close()
Catch ex As OleDbException
MessageBox.Show(ex.Message)
Finally
Connection.Dispose()
End Try
End Sub
提前谢谢你。希望代码块好转吗?
答案 0 :(得分:0)
要改变的第一件事是使用参数化查询从数据库中读取。请注意,您的代码无法找到任何内容,因为您在组合框的值之前和之后添加了空格。
然后你需要开始在一次性物体周围使用using语句,以确保正确关闭和处理
最后,OleDbDataReader的GetString方法想要在返回的字段列表中有一个数字索引,而不是字段的名称
Private Sub CbbNaamfirma_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CbbNaamfirma.SelectedIndexChanged
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
Application.StartupPath & "\Database.accdb"
Dim query = "SELECT Adres FROM TblKlanten WHERE [Naam firma] = ?"
Using Connection = New OleDb.OleDbConnection(cnString)
Using cmd = New OleDbCommand(query, Connection)
Try
Connection.Open()
cmd.Parameters.AddWithValue("@p1", CbbNaamfirma.Text)
Using Reader = cmd.ExecuteReader
While Reader.Read
Dim posAdres = Reader.GetOrdinal("Adres")
TxtAdresprev.Text = Reader.GetString(posAdres)
.... other text boxes for other fields here.....
End While
End Using
Catch ex As OleDbException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
您的连接字符串似乎也是错误的。在fielname错误之后不需要引用和错误