Keep Your DataGrid Position

Now there's a better way.

Hot Tip

LANGUAGES: C# | JavaScript

TECHNOLOGIES: Postbacks | DataGrids


Keep Your DataGrid Position

Now there's a better way.


By Jeff Prosise


In a recent article for this newsletter, I described a technique for preventing a Web form from scrolling back to the top of the page following a postback. In that tip, I noted a limitation of this technique: Namely, it works with Button controls but not with LinkButton controls, Calendar controls, or other controls that generate postbacks.


Shaun Walker, of Perpetual Motion Interactive Systems, modified this code so it works with all ASP.NET server controls - not only buttons. Here's a modified version of the original code sample, now incorporating Shaun's input:


<%@ Page Language="C#" %>




    if (Request["__SCROLLPOS"] != null &&

        Request["__SCROLLPOS"] != String.Empty) {

        int pos = Convert.ToInt32 (Request["__SCROLLPOS"]);

        Response.Write ("<body id=\"theBody\" " +

            "onscroll=\"javascript:theForm.__SCROLLPOS.value = theBody.scrollTop;\"" +

            "onload=\"javascript:theBody.scrollTop=" + pos + ";\">");



        Response.Write ("<body id=\"theBody\" " +

             "onscroll=\"javascript:theForm.__SCROLLPOS.value = theBody.scrollTop;\">");


    <form id="theForm" runat="server">

      <!-- Insert other form content here -->

      <input type="hidden" name="__SCROLLPOS" value="" />

      <asp:Button Text="Test" RunAt="server" /><br>

      <asp:LinkButton Text="Test" RunAt="server" /><br>

      <asp:Calendar RunAt="server" />





How does it work? The <body> tag contains an onscroll attribute that tracks the scroll position. The <body> tag also has an onload attribute that, following a postback, restores the last scroll position. The scroll position is transmitted to the server in a hidden <input> control, named __SCROLLPOS. Try it and you'll find that the scroll position is preserved when you click on any of the page's controls.


Jeff Prosise is author of several books, including Programming Microsoft .NET (Microsoft Press). He also is a co-founder of Wintellect (, a software consulting and education firm that specializes in .NET.




Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.