Windows Phone Developers

Wednesday, September 7, 2011

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.

Here is a situation that warrants that - we create a datatable and then create appropriate data columns

Dim oDataTable As New DataTable("BookingInfo")
        
        oDataTable.Columns.Add(New DataColumn("PassengerName"))
        oDataTable.Columns.Add(New DataColumn("JourneyDate"))
      ...
  

Then data row is created and added to the table

oDR = oDataTable.NewRow
        oDR("PassengerName") = "Dhuvaraga Prasath Mohanram"
        oDR("JourneyDate") = Now.ToString()
        oDR("Source") = "Chennai"
        oDR("Destination") = "Nellore"

        oDataTable.Rows.Add(oDR)

This can be continued till all rows are added;

DataGridView is then bound to the datatable using DataSource property

DataGridView_BookingInfo.DataSource = oDataTable
        DataGridView_BookingInfo.AutoResizeColumns()

Which gives you the screen below


Sub CreateOnTheFlyDataTable()

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

        oDataTable.Columns.Add(New DataColumn("PassengerName"))
        oDataTable.Columns.Add(New DataColumn("JourneyDate"))
        oDataTable.Columns.Add(New DataColumn("Source"))
        oDataTable.Columns.Add(New DataColumn("Destination"))

        oDR = oDataTable.NewRow
        oDR("PassengerName") = "Dhuvaraga Prasath Mohanram"
        oDR("JourneyDate") = Now.ToString()
        oDR("Source") = "Chennai"
        oDR("Destination") = "Nellore"

        oDataTable.Rows.Add(oDR)

        DataGridView_BookingInfo.DataSource = oDataTable
        DataGridView_BookingInfo.AutoResizeColumns()

    End Sub
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005