GridView丢失了DataKeys

时间:2012-08-13 14:45:45

标签: asp.net vb.net gridview

为什么当我尝试使用会话状态设置GridView的排序时,突然我的GridView不再具有DataKeys?我所做的只是将以下代码放入我的Page_Init;

Dim SortDirection As String = Session("SortDir")
Dim sortExpression As String = Session("SortExp")
If Not SortDirection Is Nothing AndAlso Not sortExpression Is Nothing Then
    If (SortDirection = "asc") Then
        GridView1.Sort(sortExpression, WebControls.SortDirection.Ascending)
    Else
        GridView1.Sort(sortExpression, WebControls.SortDirection.Descending)
    End If
End If

但是,如果我发表评论而不是其他方法,请不要再崩溃,因为我的GridView现在拥有它的DataKeys。为什么是这样?

更新

这是在上述代码到位时停止工作的确切行。

Dim UserID = GridView1.DataKeys(e.RowIndex).Value.ToString

根据调试器,GridView1有列,但它的DataKeys Count为0.我收到的错误是;

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

1 个答案:

答案 0 :(得分:2)

您希望在Page_Load(可能在If Not Page.IsPostBack阻止)事件中执行这些操作,而不是在Page_Init事件中执行。 Init用于初始化读取控件属性;加载是您通常设置属性的位置(如排序方向等)。

基本上,您的ViewState尚未加载到Page_Init。因此,您在Init中修改控件属性,然后从ViewState填充一些属性,当您的Page执行Load事件(递归调用每个服务器控件的{{Load时,这会导致意外行为1}}事件)。

您可以在MSDN上阅读关于此(有些令人困惑)的所有主题:ASP.NET Page Life Cycle Overview