Wednesday, May 11, 2011

Maintain Scrollbar Position Inside UpdatePanel After Partial PostBack

Do you want to maintain the scroll position of a GridView, Div, Panel, or whatever that is inside of an UpdatePanel after an asynchronous postback? Normally, if the updatepanel posts back, the item will scroll back to the top because it has been reloaded. What you need to do is “remember” where the item was scrolled to and jump back to there after the postback. Place the following script after the ScriptManager on your page. And since the _endRequest event of the PageRequestManager happens before the page is rendered, you’ll never even see your item move!

Code Screen Shot below :

Actual Code below :

<script type="text/javascript">

var xPos,yPos;
var prm = Sys.WebForms.PageRequestManager.getInstance();

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

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


<form runat="server">
<asp:ScriptManager id="ScriptManager1" runat="server" ScriptMode="Release" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<asp:Panel ID="Panel1" runat="server" >
<asp:Literal ID="litXML" runat="server" />