I've seen a lot of articles on the web describing how to scroll a GridView. Some of those articles may even go a little deeper and show you how to persist the scroll position across PostBacks. What I haven't been able to find is how to encapsulate the scrolling and saving/persisting of the scroll position into a custom GridView control. That is what I am going to show you how to do today.
There are many ways a developer may want to scroll their GridView (horizontal, vertical, freezing the header/footer, etc). I'm not going to go into creating a bullet proof GridView control to accomplish those tasks. My objective is to show you a technique to save/set the scroll position across PostBacks within a custom GridView control.
Here is what our end GridView control will look like. First you can see a scrollable GridView. When we scroll the GridView and then click the PostBack button, the page will perform a PostBack and the <div> will scroll itself back to where we left off.

So let's get to it. First thing we do is create a new control and inherit from the GridView. We then implement the IPostBackDataHandler to get and set our scroll position across PostBacks. You'll see the LoadPostData function accomplishes this. Take note that in line 3 I am referencing the name of my hidden field that I'll go over later. We also tell the page that our new custom GridView (Me) has data to PostBack and we can do this in the GridView's Init.
Public Function LoadPostData(ByVal postDataKey As String, ByVal postCollection As System.Collections.Specialized.NameValueCollection) As Boolean Implements System.Web.UI.IPostBackDataHandler.LoadPostData
'get and set the new scroll position
Dim postedValue As String = postCollection(Me.ClientID & "_scroll")
If Not postedValue Is Nothing Then
Dim presentValue As Integer = Me.ScrollPosition
Me.ScrollPosition = CType(postedValue, Integer)
Return Not presentValue.Equals(Me.ScrollPosition)
End If
End Function
Public Sub RaisePostDataChangedEvent() Implements System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent
'do nothing
End Sub
Private Sub ScrollingGridView_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
If Not Me.Page Is Nothing Then
'indicates that the control has data to postback
Me.Page.RegisterRequiresPostBack(Me)
End If
End Sub
In order to scroll my new custom GridView, I need to wrap my GridView with a <div> tag. To do this, I can override the Render method like so:
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
If Not Me.Page Is Nothing Then
Me.Page.VerifyRenderingInServerForm(Me)
End If
Me.PrepareControlHierarchy()
If Not Me.DesignMode Then
If String.IsNullOrEmpty(Me.ClientID) Then
Throw New HttpException("ScrollingGridView must be parented!")
End If
writer.AddAttribute(HtmlTextWriterAttribute.Id, String.Format("{0}_div", Me.ClientID), True)
writer.AddAttribute("onScroll", "saveScrollPos('" & String.Format("{0}_scroll", ClientID) & "', '" & String.Format("{0}_div", Me.ClientID) & "');")
writer.AddStyleAttribute(HtmlTextWriterStyle.OverflowY, "auto")
writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "300px")
writer.RenderBeginTag(HtmlTextWriterTag.Div)
End If
Me.RenderContents(writer)
If Not Me.DesignMode Then
writer.RenderEndTag()
End If
End Sub
Notice that when I render my <div> that I also wire in a call to my JavaScript function to save the scroll position "onScroll". At this point I have completed the PostBack data handling and I have shown you how to wrap a <div> around our GridView so we can scroll and it will call a JavaScript function "onScroll" that will save the position to a hidden field.
The next phase is to emit our JavaScripts. I always emit JavaScript in the PreRender phase of a control's lifecycle as the ClientID should be set at that point. We need a function to set the scroll position and a function to save the scroll position. Here they are:
'generate & register javascript blocks
Dim key As String = "ScrollingGridView"
Dim script As StringBuilder = New StringBuilder()
With script
.AppendLine("function saveScrollPos(whereID, whatID) {")
.AppendLine(" document.getElementById(whereID).value = document.getElementById(whatID).scrollTop;")
.AppendLine("}")
.AppendLine("function setScrollPos(whereID, whatID) {")
.AppendLine(" document.getElementById(whatID).scrollTop = (document.getElementById(whereID).value.length > 0) ? document.getElementById(whereID).value : 0;")
.AppendLine("}")
End With
If Not sm Is Nothing Then
ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), key, script.ToString(), True)
Else
Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), key, script.ToString(), True)
End If
Notice we either acquire or save the scroll position to our hidden field. Now how do we emit a hidden field inside our GridView? My first attempts were to override the Render of the GridView control and emit hidden field there. It didn't work. I ended up registering the hidden field via .NET's scripting objects instead. Check it out:
'register our hidden field to save our scroll position
If Not sm Is Nothing Then
ScriptManager.RegisterHiddenField(Me.Page, String.Format("{0}_scroll", Me.ClientID), Me.ScrollPosition.ToString())
Else
Me.Page.ClientScript.RegisterHiddenField(String.Format("{0}_scroll", Me.ClientID), Me.ScrollPosition.ToString())
End If
Notice that I assign the scroll position to the hidden field's value. Last thing we need to do is register a startup script to get the persisted scroll position from our hidden field and scroll our <div>. If you remember we created a JavaScript function for this (setScrollPosition).
'generate & register startup javascripts
key = String.Format("{0}_setScrollPos", Me.ClientID)
script = New StringBuilder()
script.AppendLine("setScrollPos('" & String.Format("{0}_scroll", Me.ClientID) & "','" & String.Format("{0}_div", Me.ClientID) & "');")
If Not sm Is Nothing Then
ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), key, script.ToString(), True)
Else
Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), key, script.ToString(), True)
End If
Putting it all Together:
In summary, we persist the scroll position of the div that wraps our GridView via a hidden field which is registered via the Page.ClientScript or ScriptManager object. We wrap the GridView with a <div> by overriding the GridView's Render method. The <div> saves the scroll position to the hidden field as the <div> is scrolled. We acquire the value stored in the hidden field via the LoadPostData function. Once a PostBack occurs, we set the scroll position of the <div> with a startup script.
ScrollingGridView_Soln.zip (97.19 kb)