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
You want to perform those actions in the
Page_Load(possibly in aIf Not Page.IsPostBackblock) event, not in thePage_Initevent. Init is for initializing or reading control properties; Load is where you generally set properties (like sort direction, etc).Basically, your
ViewStatehasn’t been loaded inPage_Inityet. So, you modify the controls properties inInit, then some properties get filled out from the ViewState, and this leads to unexpected behavior when your Page does theLoadevent (which recursively calls each server control’sLoadevent).You can read all about this (somewhat confusing) topic on MSDN: ASP.NET Page Life Cycle Overview