Converting Gridview to DataTable in VB.NET

14,922

Slight modification to your function above. If the autogenerate delete, edit or select button flags are set, the values for the fields are offset by one. The following code accounts for that:

Public Shared Function GridviewToDataTable(ByVal PassedGridView As GridView, ByRef Error_Message As String) As DataTable
    '-----------------------------------------------
    'Dim Tbl_StackSheets = New Data.DataTable

    'Tbl_StackSheets = ReportsCommonClass.GridviewToDataTable(StackSheetsGridView)

    '-----------------------------------------------

    Dim dt As New DataTable
    Dim ColInd As Integer = 0
    Dim ValOffset As Integer

    Try

        For Each col As DataControlField In PassedGridView.Columns
            dt.Columns.Add(col.HeaderText)
        Next


        If (PassedGridView.AutoGenerateDeleteButton Or PassedGridView.AutoGenerateEditButton Or PassedGridView.AutoGenerateSelectButton) Then
            ValOffset = 1
        Else
            ValOffset = 0
        End If


        For Each row As GridViewRow In PassedGridView.Rows
            Dim NewDataRow As DataRow = dt.NewRow

            ColInd = 0
            For Each col As DataControlField In PassedGridView.Columns
                NewDataRow(ColInd) = row.Cells(ColInd + ValOffset).Text.Replace(" ", "")
                ColInd += 1
            Next

            dt.Rows.Add(NewDataRow)
        Next

        Error_Message = Nothing

    Catch ex As Exception
        Error_Message = "GridviewToDataTable: " & ex.Message
    End Try


    Return dt


End Function
Share:
14,922
Laurence
Author by

Laurence

Senior Software Engineer currently in Gambling & Casino industry. Primary language is Go. React for frontend. I work remote only.

Updated on June 08, 2022

Comments

  • Laurence
    Laurence almost 2 years

    I am using this function to create datatable from gridviews. It works fine with Gridviews with AutoGenerateColumns = False and have boundfields or template fileds. But if I use it with Gridviews with AutoGenerateColumn = True I only get back an empty DataTable. Seems Gridview viewstate has been lost or something. Gridview is binded on PageLoad with If Not IsPostback. I can't think of anything else to make it work. Hope someone can help me.

    Thanks,

    Public Shared Function GridviewToDataTable(gv As GridView) As DataTable
    
        Dim dt As New DataTable
    
        For Each col As DataControlField In gv.Columns
            dt.Columns.Add(col.HeaderText)
        Next
    
        For Each row As GridViewRow In gv.Rows
            Dim nrow As DataRow = dt.NewRow
            Dim z As Integer = 0
            For Each col As DataControlField In gv.Columns
                nrow(z) = row.Cells(z).Text.Replace(" ", "")
                z += 1
            Next
            dt.Rows.Add(nrow)
        Next
        Return dt
    
    End Function