Search code examples
c#asp.netgridviewscrollpagination

Gridview Paging/Scrolling


I have a Gridview with more rows than can be displayed on the screen without scrolling. I added this to the page directive:

MaintainScrollPositionOnPostback="true"

This works great when I click edit/update/delete on a particular row the page keeps the scroll position.

However, the Gridview also has paging enabled with multiple page links. When I change pages the page keeps the scroll position at the bottom of the page.

I would like it to jump to the top of the page when switching between pages. However, I still want it to maintain scroll position on row actions edit/update/delete described above.

Any help would be greatly appreciated!


Solution

  • Here is the solution I put together:

    In the .aspx file add:

    <script>
        function ScrollToTop() {
            if (<%=(Scroll)%>) {
                window.scrollTo(0, 0);
            }
        }
    </script>
    

    ...

    <body onload="ScrollToTop()">
    

    ...

    <asp:GridView ID="GridView1 OnPageIndexChanged="GridView1_PageIndexChanged"
    

    ...


    In the code-behind .aspx.cs file added:

        protected string Scroll;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            Scroll = "false";
            Page.MaintainScrollPositionOnPostBack = true;
        }
    
        protected void GridView1_PageIndexChanged(Object sender, EventArgs e)
        {
            Scroll = "true";
        }