You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Asp.net GridView分页报错:调用目标抛出异常求助

Fixing "Exception has been thrown by the target of an invocation" in GridView Pagination

Hey there, let's dig into this error you're hitting. Looking at your stack trace, the root issue is failure to deserialize the DataTable stored in your Session object. This happens most often when the DataTable (or data within it) isn't compatible with ASP.NET's Session serialization mechanism, or if you're using a Session mode that requires strict serialization.

Here are actionable fixes to resolve this:

1. Replace Session Storage with a Reloadable Data Source

Storing full DataTables in Session is prone to serialization issues, especially across app domain recycles or non-InProc Session modes. Instead, refetch the data directly when handling pagination:

Protected Sub gv_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
    Try
        ' Replace GetGridData() with your actual method to fetch data from DB/API
        Dim gridData As DataTable = GetGridData()
        gv.DataSource = gridData
        gv.PageIndex = e.NewPageIndex
        gv.DataBind()
    Catch ex As Exception
        ' Don't swallow exceptions! Log or display details for debugging
        System.Diagnostics.Debug.WriteLine($"Pagination Error: {ex.ToString()}")
        lblErrorMessage.Text = "Failed to load page. Please try again."
    End Try
End Sub

This avoids serialization entirely and ensures you're always working with fresh, valid data.

2. Serialize the DataTable as JSON (Alternative to Raw Session Storage)

If you need to keep using Session, serialize the DataTable to a JSON string first (this avoids binary serialization conflicts):
First, add the Newtonsoft.Json NuGet package to your project. Then update your code:

' When storing data to Session (do this where you originally populate the DataTable)
Session("Data") = Newtonsoft.Json.JsonConvert.SerializeObject(yourOriginalDataTable)

' In your pagination handler
Protected Sub gv_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
    Try
        If Not Session("Data") Is Nothing Then
            Dim jsonData As String = Session("Data").ToString()
            Dim gridData As DataTable = Newtonsoft.Json.JsonConvert.DeserializeObject(Of DataTable)(jsonData)
            gv.DataSource = gridData
            gv.PageIndex = e.NewPageIndex
            gv.DataBind()
        End If
    Catch ex As Exception
        System.Diagnostics.Debug.WriteLine($"Pagination Error: {ex.ToString()}")
    End Try
End Sub

JSON serialization is more reliable for complex objects like DataTables in Session.

3. Check Session Mode and Serialization Requirements

If you're using a Session mode other than InProc (like StateServer or SQLServer), all objects stored in Session must be marked as serializable. For custom DataTable subclasses, add the <Serializable> attribute:

<Serializable()>
Public Class CustomDataTable
    Inherits DataTable
    ' Your custom logic here
End Class

Also, verify your web.config's sessionState setting:

<sessionState mode="InProc" cookieless="false" timeout="20" />

InProc is less strict about serialization, but it's still not 100% reliable for DataTables.

4. Never Use Empty Catch Blocks

Your current code swallows exceptions entirely, which makes debugging impossible. Always log or display the full exception details (at least during development) to get insight into what's breaking.


内容的提问来源于stack exchange,提问作者chosenOne Thabs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:14:14