Click here to Skip to main content
15,897,226 members
Articles / Programming Languages / Visual Basic

DataGrid101: Using Windows.Forms DataGrid

Rate me:
Please Sign up or sign in to vote.
4.70/5 (73 votes)
14 May 2003CPOL8 min read 601.7K   3.2K   147  
Tutorial on the usage of Windows.Forms.DataGrid
Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents CarsDataAdapter As System.Data.OleDb.OleDbDataAdapter
    Friend WithEvents OleDbSelectCommand1 As System.Data.OleDb.OleDbCommand
    Friend WithEvents CarsDbConnection As System.Data.OleDb.OleDbConnection
    Friend WithEvents ManufacturerDataAdapter As System.Data.OleDb.OleDbDataAdapter
    Friend WithEvents OleDbSelectCommand2 As System.Data.OleDb.OleDbCommand
    Friend WithEvents TypesDataAdapter As System.Data.OleDb.OleDbDataAdapter
    Friend WithEvents OleDbSelectCommand3 As System.Data.OleDb.OleDbCommand
    Friend WithEvents MyCarsDataSet As JoinBasedCars.CarsDataSet
    Friend WithEvents DataGrid1 As System.Windows.Forms.DataGrid
    Friend WithEvents MyTableStyle As System.Windows.Forms.DataGridTableStyle
    Friend WithEvents MyGridViewDataSet As JoinBasedCars.GridViewDataSet
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents NameColumn As System.Windows.Forms.DataGridTextBoxColumn
    Friend WithEvents MakeColumn As System.Windows.Forms.DataGridTextBoxColumn
    Friend WithEvents LicenseColumn As System.Windows.Forms.DataGridTextBoxColumn
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.CarsDataAdapter = New System.Data.OleDb.OleDbDataAdapter()
Me.OleDbSelectCommand1 = New System.Data.OleDb.OleDbCommand()
Me.CarsDbConnection = New System.Data.OleDb.OleDbConnection()
Me.ManufacturerDataAdapter = New System.Data.OleDb.OleDbDataAdapter()
Me.OleDbSelectCommand2 = New System.Data.OleDb.OleDbCommand()
Me.TypesDataAdapter = New System.Data.OleDb.OleDbDataAdapter()
Me.OleDbSelectCommand3 = New System.Data.OleDb.OleDbCommand()
Me.MyCarsDataSet = New JoinBasedCars.CarsDataSet()
Me.DataGrid1 = New System.Windows.Forms.DataGrid()
Me.MyGridViewDataSet = New JoinBasedCars.GridViewDataSet()
Me.MyTableStyle = New System.Windows.Forms.DataGridTableStyle()
Me.Label1 = New System.Windows.Forms.Label()
Me.NameColumn = New System.Windows.Forms.DataGridTextBoxColumn()
Me.MakeColumn = New System.Windows.Forms.DataGridTextBoxColumn()
Me.LicenseColumn = New System.Windows.Forms.DataGridTextBoxColumn()
CType(Me.MyCarsDataSet, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.MyGridViewDataSet, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'CarsDataAdapter
'
Me.CarsDataAdapter.SelectCommand = Me.OleDbSelectCommand1
Me.CarsDataAdapter.TableMappings.AddRange(New System.Data.Common.DataTableMapping() {New System.Data.Common.DataTableMapping("Table", "Cars", New System.Data.Common.DataColumnMapping() {New System.Data.Common.DataColumnMapping("license", "license"), New System.Data.Common.DataColumnMapping("typeID", "typeID")})})
'
'OleDbSelectCommand1
'
Me.OleDbSelectCommand1.CommandText = "SELECT license, typeID FROM Cars"
Me.OleDbSelectCommand1.Connection = Me.CarsDbConnection
'
'CarsDbConnection
'
Me.CarsDbConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Password="""";User ID=Admin;Data Source=..\..\cars" & _
".mdb;Mode=Share Deny None;Extended Properties="""";Jet OLEDB:System database="""";Je" & _
"t OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet OLEDB:Engine Type=5;" & _
"Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:" & _
"Global Bulk Transactions=1;Jet OLEDB:New Database Password="""";Jet OLEDB:Create S" & _
"ystem Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Local" & _
"e on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=" & _
"False"
'
'ManufacturerDataAdapter
'
Me.ManufacturerDataAdapter.SelectCommand = Me.OleDbSelectCommand2
Me.ManufacturerDataAdapter.TableMappings.AddRange(New System.Data.Common.DataTableMapping() {New System.Data.Common.DataTableMapping("Table", "Manufacturer", New System.Data.Common.DataColumnMapping() {New System.Data.Common.DataColumnMapping("ManufacturerID", "ManufacturerID"), New System.Data.Common.DataColumnMapping("ManufacturerName", "ManufacturerName")})})
'
'OleDbSelectCommand2
'
Me.OleDbSelectCommand2.CommandText = "SELECT ManufacturerID, ManufacturerName FROM Manufacturer"
Me.OleDbSelectCommand2.Connection = Me.CarsDbConnection
'
'TypesDataAdapter
'
Me.TypesDataAdapter.SelectCommand = Me.OleDbSelectCommand3
Me.TypesDataAdapter.TableMappings.AddRange(New System.Data.Common.DataTableMapping() {New System.Data.Common.DataTableMapping("Table", "Types", New System.Data.Common.DataColumnMapping() {New System.Data.Common.DataColumnMapping("typeID", "typeID"), New System.Data.Common.DataColumnMapping("typeName", "typeName"), New System.Data.Common.DataColumnMapping("manufacturerID", "manufacturerID")})})
'
'OleDbSelectCommand3
'
Me.OleDbSelectCommand3.CommandText = "SELECT manufacturerID, typeID, typeName FROM Types"
Me.OleDbSelectCommand3.Connection = Me.CarsDbConnection
'
'MyCarsDataSet
'
Me.MyCarsDataSet.DataSetName = "CarsDataSet"
Me.MyCarsDataSet.Locale = New System.Globalization.CultureInfo("he-IL")
Me.MyCarsDataSet.Namespace = "http://www.tempuri.org/CarsDataSet.xsd"
'
'DataGrid1
'
Me.DataGrid1.Anchor = (((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
            Or System.Windows.Forms.AnchorStyles.Left) _
            Or System.Windows.Forms.AnchorStyles.Right)
Me.DataGrid1.DataMember = "CarView"
Me.DataGrid1.DataSource = Me.MyGridViewDataSet
Me.DataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText
Me.DataGrid1.Name = "DataGrid1"
Me.DataGrid1.Size = New System.Drawing.Size(272, 204)
Me.DataGrid1.TabIndex = 0
Me.DataGrid1.TableStyles.AddRange(New System.Windows.Forms.DataGridTableStyle() {Me.MyTableStyle})
'
'MyGridViewDataSet
'
Me.MyGridViewDataSet.DataSetName = "GridViewDataSet"
Me.MyGridViewDataSet.Locale = New System.Globalization.CultureInfo("en-US")
Me.MyGridViewDataSet.Namespace = "http://tempuri.org/GridViewDataSet.xsd"
'
'MyTableStyle
'
Me.MyTableStyle.DataGrid = Me.DataGrid1
Me.MyTableStyle.GridColumnStyles.AddRange(New System.Windows.Forms.DataGridColumnStyle() {Me.NameColumn, Me.MakeColumn, Me.LicenseColumn})
Me.MyTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText
Me.MyTableStyle.MappingName = "CarView"
'
'Label1
'
Me.Label1.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left) _
            Or System.Windows.Forms.AnchorStyles.Right)
Me.Label1.Location = New System.Drawing.Point(8, 212)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(264, 72)
Me.Label1.TabIndex = 1
Me.Label1.Text = "This sample shows how one can perform a join on the client side. The original dat" & _
"a set is MyCarsDataSet and MyGridViewDataSet holds the join. This example is rea" & _
"d-only."
'
'NameColumn
'
Me.NameColumn.Format = ""
Me.NameColumn.FormatInfo = Nothing
Me.NameColumn.HeaderText = "Name"
Me.NameColumn.MappingName = "type"
Me.NameColumn.ReadOnly = True
Me.NameColumn.Width = 75
'
'MakeColumn
'
Me.MakeColumn.Format = ""
Me.MakeColumn.FormatInfo = Nothing
Me.MakeColumn.HeaderText = "Make"
Me.MakeColumn.MappingName = "make"
Me.MakeColumn.ReadOnly = True
Me.MakeColumn.Width = 75
'
'LicenseColumn
'
Me.LicenseColumn.Format = ""
Me.LicenseColumn.FormatInfo = Nothing
Me.LicenseColumn.HeaderText = "Plate"
Me.LicenseColumn.MappingName = "license"
Me.LicenseColumn.ReadOnly = True
Me.LicenseColumn.Width = 75
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(272, 285)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.Label1, Me.DataGrid1})
Me.Name = "Form1"
Me.Text = "Client-side join"
CType(Me.MyCarsDataSet, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.MyGridViewDataSet, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)

    End Sub

#End Region

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' When you load data into a DataSet as several tables, displaying 
' it corectly in a grid turns out to be a pain.
' The SQL type JOIN is simply not avaiable at this moment. Until
' someone writes this class, we need to do it ourselves
' (1) Create new XSD with table in the required structure
' (2) Fill it by looping on the child table - see "loadDataToViewDS()
' (3) Bind to this table (note that design time support is a bit lacking)
' (4) Updating DB will require a loop with references to the other side
'     It may be a good idea to hold ids (hidden by grid style) for this 
'     purpose (but this will also require combo work)
' An alternative is creating Object based viewers. It is essentially the same
' Some non-working solutions people may suggest:
' (a) Use DataView - No. It supports filter & sort - not join.
' (b) bind to relation - No. Shows hierarchiacal table - not simple table

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Load data from DB (usualy done on server side)
        ManufacturerDataAdapter.Fill(MyCarsDataSet)
        TypesDataAdapter.Fill(MyCarsDataSet)
        CarsDataAdapter.Fill(MyCarsDataSet)

        'Transfer data to required structure
        loadDataToViewDS()

        'link grid
        DataGrid1.DataMember = "CarView"
    End Sub

    Private Sub loadDataToViewDS()
        Dim carRec As DataRow
        Dim viewRec As DataRow
        For Each carRec In MyCarsDataSet.Tables("Cars").Rows
           viewRec = MyGridViewDataSet.Tables("CarView").NewRow
           viewRec("license") = carRec("license")
           viewRec("type") = carRec.GetParentRow("TypesCars").Item("typeName")
           viewRec("make") = carRec.GetParentRow("TypesCars").GetParentRow("ManufacturerTypes").Item("ManufacturerName")
           MyGridViewDataSet.Tables("CarView").Rows.Add(viewRec)
        Next
    End Sub


End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Israel Israel
Omri started coding way back in the good ol' Apple ][ days. His first commercial (acutally governmental) software package was released 1986.
In the 90's Omri programmed C and C++, and managed larger development teams using MFC/COM.
In the last 3 years he is into Java server programming, and while he loves the language and community, he has many reservations. Maybe this is why .Net feels like comming back home...

Comments and Discussions