Tuesday, 31 July 2012

How to create DataTable on the fly and add Rows (data) using VB.NET/C#


How to Populate DataGridView on the fly using VB.NET

Not all data come from a database table;
at times we need to create in on the fly.
we create a datatable and then create appropriate data columns.

Tested Code..

Dim oDataTable As New DataTable("CustomerInfo")
        Dim oDR As DataRow

        oDataTable.Columns.Add(New DataColumn("Name"))
        oDataTable.Columns.Add(New DataColumn("Date"))
        oDataTable.Columns.Add(New DataColumn("Address"))
        oDataTable.Columns.Add(New DataColumn("ContactNum"))
 â€¦.

Then data row is created and added to the table


  oDR = oDataTable.NewRow
        oDR("Name") = "shree"
        oDR("Date") = Now.ToString()
        oDR("Address") = "Gujarat"
        oDR("ContactNum") = "09898989898"

        oDataTable.Rows.Add(oDR)

This can be continued till all rows are added;

DataGridView is then bound to the datatable using DataSource property

  DataGridView1.DataSource = oDataTable
        DataGridView1.AutoResizeColumns()

Which gives you the screen below


 
--------------------------------------------------------------------------------
Public Class Form1

    Private Sub Form1_Load(sender As System.Object,
 e As System.EventArgs) Handles MyBase.Load

        CreateOnTheFlyDataTable()
    End Sub

    Sub CreateOnTheFlyDataTable()
        Dim oDataTable As New DataTable("CustomerInfo")
        Dim oDR As DataRow

        oDataTable.Columns.Add(New DataColumn("Name"))
        oDataTable.Columns.Add(New DataColumn("Date"))
        oDataTable.Columns.Add(New DataColumn("Address"))
        oDataTable.Columns.Add(New DataColumn("ContactNum"))

        oDR = oDataTable.NewRow
        oDR("Name") = "shree"
        oDR("Date") = Now.ToString()
        oDR("Address") = "Gujarat"
        oDR("ContactNum") = "09898989898"

        oDataTable.Rows.Add(oDR)
        DataGridView1.DataSource = oDataTable
        DataGridView1.AutoResizeColumns()
    End Sub
End Class

0 comments:

Post a Comment