我想用SQL返回的数据填充DataGridView。所以这是我的代码 [我提供的原因有些人可能认为我在尝试之前寻求帮助]
我希望DataGridView能够被来自SQL的数据填充,而不是显示所有记录。
SQL “选择*来自书籍,其中title ='php%'按标题排序;”
Imports System.Data
Imports System.Data.SqlClient
Public Class frmMain
Dim connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist" & " Security Info=True"
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.BooksTableAdapter.Fill(Me.TblBooks.books)
End Sub
Private Sub txtTerm_TextChanged() Handles txtTerm.TextChanged
If Trim(txtTerm.Text) = "" Then Exit Sub
Dim tblCustomBooks As New DataTable
Dim adpBooks As New OleDb.OleDbDataAdapter("Select * From books where title='php%' Order By Title", _
'"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist" & " Security Info=True")
adpBooks.Fill(tblCustomBooks)
BooksTableAdapter.Fill(tblCustomBooks)
'Dim myConnection As SqlConnection
'Dim myCommand As SqlDataAdapter
'myConnection = New SqlConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist" & " Security Info=True")
'myCommand = New SqlDataAdapter("Select * From books where title='php%' Order By Title", myConnection)
'Dim ds As DataSet = New DataSet()
'myCommand.Fill(ds)
'gridTable.DataSource = ds
End Sub
答案 0 :(得分:2)
看起来你已经尝试了很多不同的东西,但是从你的代码中看不出你尝试过它们的顺序。根据代码的当前版本,你遗漏了两件事:
首先,OleDBConnection对象与OleDbDataAdapter一起使用。
其次,您没有为DataGridView
的DataSource属性分配任何内容,因此不会显示任何内容。
此外,您似乎正在使用两个不同的OleDbDataAdapter(或者可能是两个不同的DataAdapter)来填充tblCustomBooks
,因此根据BooksTableAdapter
设置的内容可能也会导致您出现问题。< / p>
试试这个:
Private Sub txtTerm_TextChanged() Handles txtTerm.Changed
If Trim(txtTerm.Text) = "" Then Exit Sub
Dim tblCustomBooks As New DataTable
Using conn As New OleDbConnection(connectionString)
Dim adpBooks As New OleDbDataAdapter("SELECT * FROM books WHERE title = 'php%' ORDER BY title", conn)
adpBooks.Fill(tblCustomBooks)
gridTable.DataSource = tblCustomBooks
End Using
End Sub
请参阅:
答案 1 :(得分:2)
在你的SQL语句中尝试[WHERE Title LIKE'php%']而不是[WHERE Title ='php%']。
我遇到了与MS SQL类似的问题,这就是修复。我不确定Jet提供程序的SQL语法是否相同,但至少值得一试。
HTH
答案 2 :(得分:0)
col-sm-push