Quantcast
Channel: SourceHints » classes
Viewing all articles
Browse latest Browse all 5

How to convert Datagridview Data to Datatable

$
0
0

Post to Twitter

Converting datagridview row data into datatable

  • Requirements: Microsoft Visual Studio 2005/2008/2010
  • Programming Level: Advance
  • Language: Microsoft Visual Basic.Net

Scenario:

Datagridview is an essential component of visual studio wherein you could populate data on it by either a databinding or manual inserting of data. Being a visual basic programmer for almost 8 years, I’d rather choose to insert data on datagridview manually rather than databinding in such a manner you take control your program, if something’s happen you can easily debug your code. Whether what method are you going to use to populate data on datagridview it doesn’t matter in either way.

Challenge:

We all know that its very simple to populate data on datagridview by either the Datatable or dataset as your datasource as shown below:

dtgTestgrid.Datasource=mydataset.tables(0) or:

For Each drow as DataRow in mydataset.tables(0).rows
     dtgTestgrid.rows.add(drow("column1"),drow("column2"),drow("column3"))
Next

This is how to populate data, how about the opposite way?

From Datagridview to Datatable:

I am going to show you how to convert the data from datagridview to a DataTable by using only for each statement. This procedure creates a dynamic datatable that is dependent on the structure of a datagridview, so whatever the structure generated or created with the datagridview will be the structure of the generated datatable, you only need to provide two parameters for this function, the Datagridview object and the Datatable name in a form of a string.

From Datatable to XML file:

To convert Datatable to an xml file you can use the WriteXml method of datatable object.

dim xmlPath as string =”c:\DatagridviewXML.xml”

DataGridViewToDataTable(dtgTestgrid,”SampleData”).WriteXml(xmlPath)

The Code:

Public Shared Function IfNullObj(ByVal o As Object, Optional ByVal DefaultValue As String = "") As String
        Dim ret As String = ""
        Try
            If o Is DBNull.Value Then
                ret = DefaultValue
            Else
                ret = o.ToString
            End If
            Return ret
        Catch ex As Exception
            Return ret
        End Try
    End Function
Public Shared Function DataGridViewToDataTable(ByVal dtg As DataGridView,
    Optional ByVal DataTableName As String = "myDataTable") As DataTable
    Try
         Dim dt As New DataTable(DataTableName)
         Dim row As DataRow
         Dim TotalDatagridviewColumns As Integer = dtg.ColumnCount - 1
         'Add Datacolumn
         For Each c As DataGridViewColumn In dtg.Columns
             Dim idColumn As DataColumn = New DataColumn()
             idColumn.ColumnName = c.Name
             dt.Columns.Add(idColumn)
         Next
         'Now Iterate thru Datagrid and create the data row
         For Each dr As DataGridViewRow In dtg.Rows
             'Iterate thru datagrid
             row = dt.NewRow 'Create new row
             'Iterate thru Column 1 up to the total number of columns
             For cn As Integer = 0 To TotalDatagridviewColumns
                  row.Item(cn) = IfNullObj(dr.Cells(cn).Value) ' This Will handle error datagridviewcell on NULL Values
             Next
             'Now add the row to Datarow Collection
             dt.Rows.Add(row)
         Next
         'Now return the data table
         Return dt
   Catch ex As Exception
         Return Nothing
   End Try
End Function

Explanation:

The Function above generates a Datable,  it uses the two parameters (dtg and DataTableName) as the basic requirements. It dynamically creates the data columns derived from datagridview columns and thus iterates from datagridview rows to insert or populate data on generated datatable, after the iterations iterate on datagridview it thus return the datatable object “dt”. So From Datagridview you can now convert data from Datagridview to either an xml as shown below:

dim xmlPath as string =”c:\DatagridviewXML.xml”

DataGridViewToDataTable(dtgTestgrid,”SampleData”).WriteXml(xmlPath)

So Just call the Function and passing the two required parameters, since that this function returns a datatable you can use WriteXml method of a datatable object to convert the data on datagridview to an XML format via xmlPath filename.

Post to Twitter

Keywords: , , , , , , , , ,

Other reading this article are also reading these:


Viewing all articles
Browse latest Browse all 5

Trending Articles