What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleBind a DataGrid to a DataTable with read-only columns in VB .NET
DescriptionThis example shows how to bind a DataGrid to a DataTable with read-only columns in VB .NET.
KeywordsDataGrid, DataTable, bind, ADO.NET, data, database, read only
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 gets the Addresses DataTable in the DataSet and sets the ReadOnly property for its FirstName and LastName columns to True. It then sets the DataGrid control's DataSource property to the DataTable.
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 " & _

    ' 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, _

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

    ' Make FirstName and LastName read-only.
    Dim dt_addresses As DataTable = _
    dt_addresses.Columns("FirstName").ReadOnly = True
    dt_addresses.Columns("LastName").ReadOnly = True

    ' Bind the DataGrid to the DataTable.
    dgContacts.DataSource = dt_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 update the data.
' Save changes to the data.
Private Sub Form1_Closing(ByVal sender As Object, ByVal e _
    As System.ComponentModel.CancelEventArgs) Handles _
    ' Use a CommandBuilder to make the INSERT,
    ' UPDATE, and DELETE commands as needed.
    Dim command_builder As New _

    ' Update the database.
        m_da_Addresses.Update(m_DataSet, "Addresses")
    Catch ex As Exception
    End Try
End Sub
Note that because the FirstName and LastName fields are read-only, the user cannot create new values for them when creating a new record. That lessens the usefulness of the example somewhat.

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.