windowsgm
windowsgm

Reputation: 1616

GridView Loses DataKeys

Why is it that when I try to set my GridView's sorting using session states that suddenly my GridView no longer has DataKeys? All I did was put the following code into my 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

But if I comment this out than my other methods don't crash out any more as my GridView now has it's DataKeys. Why is this?

UPDATE

This is the exact line that stops working when the above code is in place.

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

According to debugger GridView1 has columns but it's DataKeys Count is 0. The error I receive is;

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

Upvotes: 1

Views: 1325

Answers (1)

Josh Darnell
Josh Darnell

Reputation: 11433

You want to perform those actions in the Page_Load (possibly in a If Not Page.IsPostBack block) event, not in the Page_Init event. Init is for initializing or reading control properties; Load is where you generally set properties (like sort direction, etc).

Basically, your ViewState hasn't been loaded in Page_Init yet. So, you modify the controls properties in Init, then some properties get filled out from the ViewState, and this leads to unexpected behavior when your Page does the Load event (which recursively calls each server control's Load event).

You can read all about this (somewhat confusing) topic on MSDN: ASP.NET Page Life Cycle Overview

Upvotes: 2

Related Questions