Search code examples
vb.netoledb

Fill DataGridView with data from SQL


I want to fill a DataGridView with data returned from a SQL. So here is my code [I provided cause some people may think I'm asking for help before trying myself]

I want the DataGridView to be filled by a data from SQL not to show all the records.

The SQL "Select * From books where title='php%' Order By Title;"

useless code :( :'( :<

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

Solution

  • Looks like you've tried a number of different things, but it's not apparent from your code what order you tried them in. Based on the current version of your code, you're missing two things:

    First, an OleDBConnection object to use with the OleDbDataAdapter.

    Second, you're not assigning anything to the DataGridViews DataSource property, so nothing will show up.

    Also, you appear to be using two different OleDbDataAdapters (or maybe two different DataAdapters altogether) to fill tblCustomBooks, so depending on what BooksTableAdapter is set up as may also be causing you problems.

    Try this:

    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
    

    See:

    DataGridView.DataSource Property

    OleDbDataAdapter Class