asp.netvb.netgridviewdataboundfailed-to-load-viewstate

How can i add a row to a data-bound gridview without causing viewstate errors?


I'm trying to add a row grouping row to my data-bound gridview. It works fine on the first response, but at the postback i got the "Failed to load viewstate" error.

There is the code for the GridView's RowDataBound event:

Private Sub AddGroupingRow(ByRef eRow As GridViewRow, ByVal Css As String, ByVal ColSpan As Integer, ByVal Txt As String)
    Dim cell As New TableCell()
    cell.ColumnSpan = ColSpan
    cell.CssClass = "Spacing FieldCell"
    cell.Text = Txt

    Dim row As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal)
    row.CssClass = Css
    row.Cells.Add(cell)

    Dim tbl As Table
    tbl = eRow.Parent
    tbl.Rows.AddAt(eRow.RowIndex + 1, row)
End Sub

Private Prev_Client_ID As Integer = -1
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim dr As Data.DataRowView = TryCast(e.Row.DataItem, Data.DataRowView)

        If dr IsNot Nothing AndAlso dr.Row.RowState <> Data.DataRowState.Added Then
            Dim Client_ID As Integer = dr.Item("Client_ID")

            If Client_ID <> Prev_Client_ID Then AddGroupingRow(e.Row, "Group", 8, dr.Item("Client_Name"))
            Prev_Client_ID = Client_ID
        End If

    End If
End Sub

I know that it's easier to create the grouping rows at the datasource, but deriving from this code, i want to create some base to other grids at the site.


Solution

  • Try this link. it should help you. I too had the same problem. The only way to resolve is a proper understanding of viewstate.