65.9K
CodeProject is changing. Read more.
Home

Working with an unbound datagrid

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.08/5 (41 votes)

Mar 12, 2004

CPOL
viewsIcon

147113

downloadIcon

1961

This article explains about how to manage the unbounded datagrid for storing and editing values.

Introduction

This article explains about how to manage the unbounded datagrid for storing and editing values. In earlier versions of Visual Basic, We make use of MS Flex Grid to manipulate the spreadsheet type of data. In Vb.Net you can use the datagrid for the same purpose and can add columns and rows dynamically. Let us see this in the example given below

  • Open a VisualBasic Project
  • Drop a Datagrid in the design view
  • Drop a Button
  • Change the button name property to btnAdd and text property to Add
  • Now in the general declaration section of the class declare these variables

Example

'This is the table which will hold our columns and rows

Dim Tbl As New DataTable()
'This is the column type which will be added to the Datatable
Dim Col1 As New DataColumn()
Dim Col2 As New DataColumn()
Dim Col3 As New DataColumn()

'In the general section declare a procedure to format the datatable
  Private Sub FormatGrid()

        'Define column 1
        'Specify the column data type  
        Col1.DataType = System.Type.GetType("System.Int32")
        'This name is to identify the column
        Col1.ColumnName = "No"
        'This will enable automatically increment the data 
        Col1.AutoIncrement = True
        'This value will be displayed in the header of the column
        Col1.Caption = "No"
        'This will make this column read only,Since it is autoincrement
        Col1.ReadOnly = true
        'Now add this column to the datatable
        Tbl.Columns.Add(Col1)
        'Repeat the same procedure         
        'Define Column 2
        Col2.DataType = System.Type.GetType("System.String")
        Col2.ColumnName = "Name"
        Col2.Caption = "Name"
        Col2.ReadOnly = False
        Tbl.Columns.Add(Col2)
        'Define Column 3
        Col3.DataType = System.Type.GetType("System.String")
        Col3.ColumnName = "Address"
        Col3.Caption = "Address"
        Col3.ReadOnly = False
        Tbl.Columns.Add(Col3)
      'BIND THE DATATABLE TO THE DATAGRID
       DataGrid1.DataSource = Tbl
    End Sub
'now call this procedure in the load event of the form
    FormatGrid()

' To add rows dynamically in the click event of the button, 
' include the code in the click event of the btnAdd
       'Create a row type variable

        Dim r As DataRow

        'Add a new row
        r = Tbl.NewRow()
        'Specify the  col name to add value for the row
        r("Name") = "ManojRajan"
        r("Address") = "New Delhi"
        'Add the row to the tabledata
        Tbl.Rows.Add(r)