我正在使用此函数从gridviews创建数据表。它适用于具有AutoGenerateColumns = False的Gridviews,并具有boundfields或模板fileds。但是如果我将它与Gridview一起用于AutoGenerateColumn = True,我只会得到一个空的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
答案 0 :(得分:2)
对您上面的功能稍作修改。如果设置了自动生成删除,编辑或选择按钮标志,则字段的值将偏移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