Skip to content

How to maintain scroll position of a gridview

April 12, 2013

There are two different approaches depending on whether the gridview is inside an UpdatePanel or not. If it’s not inside an UpdatePanel, then put javascript caller in div definition : “onscroll=SetDivPosition();”

    // Maintain Gridview scroll position. (Partial Postback (UpdatePanel) version)-----
    var yPos;
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    function BeginRequestHandler(sender, args) {
        if ($get('<%= divGridview.ClientID%>') != null) {
            yPos = $get('<%= divGridview.ClientID%>').scrollTop;
        }
    }

    function EndRequestHandler(sender, args) {
        if ($get('<%= divGridview.ClientID%>') != null) {
            $get('<%= divGridview.ClientID%>').scrollTop = yPos;
        }
    }

    prm.add_beginRequest(BeginRequestHandler);
    prm.add_endRequest(EndRequestHandler);
 
    // Maintain Gridview scroll position. (Non-UpdatedPanel version)-----
    window.onload = function () {
        var strCook = document.cookie;
        if (strCook.indexOf("!~") != 0) {
            var intS = strCook.indexOf("!~");
            var intE = strCook.indexOf("~!");
            var strPos = strCook.substring(intS + 2, intE);
            var divGridView = document.getElementById("<%= divGridview.ClientID%>")

            if (divGridView != null) {
                //remembered scroll position might be out of range if the length of GridView was shortened
                if (strPos > divGridView.style.height * 0.92) strPos = divGridView.style.height * 0.92;
                divGridView.scrollTop = strPos;

            }
        }
    }
  
    function SetDivPosition() {
            var intY = document.getElementById("<%= divGridview.ClientID%>").scrollTop;
        //document.title = intY;    //it changes the title of IE tab/window (side effect. disabled.)
        document.cookie = "yPos=!~" + intY + "~!";
    } 
Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: