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.

有帮助吗?

解决方案

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

其他提示

After some thinking, the answer could not be simpler: disable the viewstate of the gridview.

I was re-binding the datasource at every paging or sorting, so the need for the viewstate was minimum, except for the PageSize and PageIndex, that i became forced to keep track manually.

This is a considerable trade-off: things like PageSize and PageIndex must be managed manually afterwards, since their state are keeped by the ViewState.

So, even doing exactly what i was meant to do, i've decided to adopt an simple alternative solution:

If Cliente_ID <> Cliente_ID_Anterior Then
    For i As Integer = 0 To e.Row.Cells.Count - 1
        e.Row.Cells(i).Style("border-top") = "solid 1px #777777"
    Next
    e.Row.Cells(0).Style("border-bottom") = "none"
Else
    e.Row.Cells(0).Text = "&nbsp;"
    e.Row.Cells(0).Style("border-top") = "none"
    e.Row.Cells(0).Style("border-bottom") = "none"
End If

It still groups the column, but in another way, and is more sort friendly. I could use rowspans and turn cells invisible, but it would be harder to keep. Besides, I'll need to paint the line when the user moves the mouse over it, and a rowspan would hinder a lot.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top