首页 > 解决方案 > 为什么gridview不保留分页之间的复选框值?

问题描述

我正在尝试在分页之间存储复选框值,因此如果我从一页转到另一页并返回,选中的复选框将持续存在。

Protected Sub gv_InforWO_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
       Try
            gv_InforWO.PageIndex = e.NewPageIndex

            If chkFiltersAvailable.Checked = False Then
                chkSelectAll.Checked = False
                BindGridInfoWO()
                'btnSync_Click(Nothing, Nothing)
            Else

                BindGridInfoWO()
                ' btnSync_Click(Nothing, Nothing)
            End If

            'checkbox persistence code
            Dim d As Integer = gv_InforWO.PageCount
            Dim values() As Boolean = New Boolean((gv_InforWO.PageSize) - 1) {}
            Dim chb As CheckBox
            Dim count As Integer = 0
            Dim i As Integer = 0
            Do While (i < gv_InforWO.Rows.Count)
                chb = CType(gv_InforWO.Rows(i).FindControl("chkSelect"), CheckBox)
                If (Not (chb) Is Nothing) Then
                    values(i) = chb.Checked
                End If

                i = (i + 1)
            Loop

            Session(("page" + CType(gv_InforWO.PageIndex, String))) = values


        Catch ex As Exception
             lblWaitingMsg.Text= ex.Message 
        End Try
    End Sub

预渲染

Protected Sub gv_InforWO_PreRender(sender As Object, e As EventArgs)
        Try
            If (Not (Session(("page" + CType(gv_InforWO.PageIndex, String)))) Is Nothing) Then
                Dim chb As CheckBox
                Dim values() As Boolean = CType(Session(("page" + CType(gv_InforWO.PageIndex, String))), Boolean())
                Dim i As Integer = 0
                Do While (i < gv_InforWO.Rows.Count)
                    chb = CType(gv_InforWO.Rows(i).FindControl("chkSelect"), CheckBox)
                    chb.Checked = values(i)
                    i = (i + 1)
                Loop

            End If
        Catch ex As Exception

        End Try
       
    End Sub

但即使我勾选框,它也不会保留该值并且会出现错误。

标签: asp.netvb.netcheckboxgridviewwebforms

解决方案


如果您的复选框数据绑定到某些东西,我的猜测是您需要更新 PageIndexChanging 上的源数据以使其保持不变,或者如果您要像在代码示例中那样将值存储在会话中,请更新这些值 OnRowDataBound 而不是整个网格的预渲染。


推荐阅读