What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleUse a bound DataGrid in VB.NET
DescriptionThis example shows how to use a bound DataGrid in VB.NET.
KeywordsDataGrid, binding, bind, bound, VB.NET
CategoriesVB.NET, Controls, Database
Create an OleDbDataAdapter. Use the DataAdapter Configuration Wizard to configure the adapter. This builds a database connection for the adapter and defines the SQL query used to select data.

Select the new adapter. Below the Properties window, click the "Generate DataSet" link. This makes a DataSet that can hold the data selected by the adapter.

Add a DataGrid to the form. Set its DataSource property to the DataSet or to one of the tables selected by the DataSet.

When the form loads, use code similar to the following to make the adapter load data into the DataSet.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
    Dim db_path As String = Application.StartupPath
    db_path = db_path.Substring(0, db_path.LastIndexOf("\"))
    db_path &= "\StudentData.mdb"
    connStudents.ConnectionString = _
        "Data Source=""" & db_path & """;" & _
        "Provider=""Microsoft.Jet.OLEDB.4.0"";" & _
        "persist security info=False"

End Sub
This example uses a query that joins two tables so the data adapter does not understand how to update the tables. If you use a simple query that selects data from a single table, the adapter may be able to update the database if the user makes changes in the DataGrid. If that's the case, use the adapter's Update method to save the changes.

For more 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.