Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleBind a DataGrid to a DataTable at run time in VB .NET
DescriptionThis example shows how to bind a DataGrid to a DataTable at run time in VB .NET.
KeywordsDataGrid, DataTable, bind, ADO.NET, data, database
CategoriesDatabase, Controls
 
When the program starts, it creates an OleDbDataAdapter to select data from a database. It creates a DataSet and uses the adapter's Fill method to load it with data. It then sets the DataGrid control's DataSource property to the Addresses DataTable in the DataSet.
 
Private m_da_Addresses As OleDbDataAdapter
Private m_DataSet As DataSet

Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
    Const SELECT_ADDRESSES As String = "SELECT * FROM " & _
        "Addresses"

    ' Get the database file name.
    Dim db_name As String = Application.StartupPath
    db_name = db_name.Substring(0, db_name.LastIndexOf("\"))
    db_name &= "\Contacts.mdb"

    ' Compose the connection string.
    Dim connect_string As String = _
          "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & db_name & ";" & _
          "Persist Security Info=False"

    ' Create a DataAdapter to load the Addresses table.
    m_da_Addresses = New OleDbDataAdapter(SELECT_ADDRESSES, _
        connect_string)

    ' Create and fill the DataSet.
    m_DataSet = New DataSet
    m_da_Addresses.Fill(m_DataSet, "Addresses")

    ' Bind the DataGrid to the DataTable.
    dgContacts.DataSource = m_DataSet.Tables("Addresses")
End Sub
 
When the program is ending, it makes an OleDbCommandBuilder object for the adapter. The adapter will use the command builder to make SQL insert, update, and delete commands as necessary to save any changes to the database.

The program then uses the adapter's Update method to save any changes to the data.

 
' Save changes to the data.
Private Sub Form1_Closing(ByVal sender As Object, ByVal e _
    As System.ComponentModel.CancelEventArgs) Handles _
    MyBase.Closing
    ' Use a CommandBuilder to make the INSERT,
    ' UPDATE, and DELETE commands as needed.
    Dim command_builder As New _
        OleDbCommandBuilder(m_da_Addresses)

    ' Update the database.
    Try
        m_da_Addresses.Update(m_DataSet, "Addresses")
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub
 
For information on database programming in VB .NET, see my book Visual Basic .NET Database Programming.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated