3

我正在使用此函数从 gridviews 创建数据表。它适用于具有 AutoGenerateColumns = False 的 Gridview 并具有绑定字段或模板文件。但是,如果我将它与 AutoGenerateColumn = True 的 Gridviews 一起使用,我只会得到一个空的 DataTable。似乎 Gridview 视图状态已经丢失或什么的。Gridview 在 PageLoad 上与 If Not IsPostback 绑定。我想不出其他任何东西可以让它发挥作用。希望可以有人帮帮我。

谢谢,

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
4

1 回答 1

4

对上面的函数稍作修改。如果设置了自动生成删除、编辑或选择按钮标志,则字段的值偏移 1。以下代码说明了这一点:

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
于 2014-09-22T18:41:23.260 回答