0

在一些 ASP.Net 代码隐藏中,我调用了SelectRow继承自System.Web.UI.WebControls.GridView.

拨打电话:

If (ProgressGrid.Rows.Count > 0) Then
    ProgressGrid.SelectRow(0)
End If

正如预期的那样,这会生成一个SelectedIndexChanged事件,由处理程序拾取:

Protected Sub ProgressGrid_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ProgressGrid.SelectedIndexChanged
    Using db As New DataContext
        Dim course = (From c In db.CourseResults
         Where c.MemberID = MemberID AndAlso c.ResultID = CInt(ProgressGrid.SelectedDataKey.Value)
         Select c).Single

        ' more code here

    End Using
End Sub

我的问题是ProgressGrid.SelectedDataKeynothing我的事件处理程序内部,导致空引用错误。在使用 Visual Studio 2010 进行调试时,我可以从调用堆栈中看到ProgressGrid.SelectRow(0)被命中并且ProgressGrid.Rows.Count大于零。那么为什么对象上的所有“Selected...”属性都ProgressGrid设置为nothingor -1?知道我做错了什么吗?

自定义 Grid 类包含覆盖默认GridView行为的此属性:

    Public Overrides Property SelectedIndex() As Integer
        Get
            If AutoPostback Or AllowSelect = False Then
                Return MyBase.SelectedIndex
            Else
                If HttpContext.Current Is Nothing Then
                    Return Nothing
                    Exit Property 'Exit if in design mode
                End If
                Dim index As String = Page.Request(Me.ClientID + "_SelectedRow")
                If (String.IsNullOrEmpty(index)) Then
                    If (ViewState("SelectedIndex") Is Nothing) Then
                        Return -1
                    Else
                        Return ViewState("SelectedIndex")
                    End If
                Else
                    ViewState.Add("SelectedIndex", index)
                    Return CType(index, Integer)
                End If
            End If
        End Get
        Set(ByVal value As Integer)
            MyBase.SelectedIndex = value
        End Set
    End Property

调试器无法显示详细信息,MyBase第一次调用MyBase.SelectedIndex = value调试器的快速监视窗口返回空引用错误。一旦我到达事件处理程序,上述属性中的断点表明它MyBase.SelectedIndexnothing,尽管试图将其设置为零。

4

1 回答 1

1

我发现ViewState在自定义网格的SelectedIndex属性中设置 解决了我的问题。这允许ViewState保存新的索引值并Get在属性上调用该方法时返回它。

Set(ByVal value As Integer)
    MyBase.SelectedIndex = value
    ViewState("SelectedIndex") = value
End Set
于 2013-06-16T21:04:12.167 回答