By default the scroll position of div tags will be reset whenever you do a postback with AJAX.
The following code can be used in you have an UpdatePanel containing a gridview in a fixed div tag and you need to enable Edit/Cancel and Update functionality of the gridview without resetting the scroll position on postbacks.
The code has been tested with IE7, FF 2.0.0.12 and Opera 9.26 and should basically work with any browser supporting the documents.getElementById() method.
Using the code
Add the following code between your <head> </head> tags
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
setScrollPos();
}
function saveScrollPos(){
document.getElementById("scrollPos").value = document.getElementById("divScroll").scrollTop;
}
function setScrollPos(){
document.getElementById("divScroll").scrollTop = document.getElementById("scrollPos").value;
}
</script>
NB! You might have to change the scrollPos name with the ClientID if your element are encapsulated in another control, masterpage e.g.
public static string scrollPos = String.Empty;
scrollPos = ((HtmlInputHidden)scrollPos).ClientID.ToString();
Then change the javascript to:
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
setScrollPos();
}
function saveScrollPos(){
document.getElementById("<%=scrollPos%>").value = document.getElementById("divScroll").scrollTop;
}
function setScrollPos(){
document.getElementById("divScroll").scrollTop = document.getElementById("<%=scrollPos%>").value;
}
</script>
Assuming that you have already added a <asp:ScriptManager> to your page, then add the following:
<input type="hidden" id="scrollPos" name="scrollPos" value="0" runat="server"/>
<asp:UpdatePanel runat="server" ID="up1" UpdateMode="always">
<ContentTemplate>
<asp:Button runat="server" ID="button1" text="Post back!" />
<div id="divScroll" style="height: 200px; overflow:auto; overflow-x:hidden; overflow-y:scroll;" onscroll="saveScrollPos();">
.... some code here that will cause the div to overflow, e.g. a gridview with a lot of rows.
</div>
</ContentTemplate>
</asp:UpdatePanel>