Introduction
This code cancel the move of the scrollbar after a Postback. It is a simple
Control based on HtmlInputHidden
which saves, before the postback, the position of the
scrollbar and moves it afterwards back to the old position. The variable
is saved in the viewstate
. This code
uses JavaScript to get the position of the scrollbar and move it.
Code
using System;
using System.Web.UI;
namespace AnnulMvtPostBack
{
public class GetPositionPostBack:
System.Web.UI.HtmlControls.HtmlInputHidden,
IPostBackDataHandler
{
public int VPos
{
get
{
if(ViewState["VPos"]==null)
{
ViewState["VPos"] = 0;
}
return (int)ViewState["VPos"];
}
set { ViewState["VPos"] = value; }
}
public int HPos
{
get
{
if(ViewState["HPos"]==null)
{
ViewState["HPos"] = 0;
}
return (int)ViewState["HPos"];
}
set { ViewState["HPos"] = value; }
}
public bool LoadPostData(String postDataKey,
System.Collections.Specialized.NameValueCollection values)
{
bool _returnV;
bool _returnH;
string Val = values[this.UniqueID].Trim();
char Eperluette = Char.Parse("&");
string[] _Val = Val.Split(Eperluette);
if(_Val.Length>1)
{
if(!HPos.ToString().Equals(_Val[0]) && _Val[0].Trim()!=null )
{
HPos= Int32.Parse(_Val[0]);
_returnH=true;
}
else _returnH=false;
if(!VPos.ToString().Equals(_Val[1]) && _Val[1].Trim()!=null )
{
VPos= Int32.Parse(_Val[1]);
_returnV=true;
}
else _returnV=false;
}
else
{
HPos = 0;
VPos=0;
return false;
}
if(_returnV || _returnH) return false;
else return false;
}
public void RaisePostDataChangedEvent()
{
}
protected override void OnPreRender(EventArgs e)
{
string _start = "<script language="'Javascript'">onscroll = function(){";
_start += "document.getElementById('" + this.UniqueID +
"').value = document.body.scrollLeft+'&'+document.body.scrollTop;";
_start += "}</script>";
if(!Page.IsClientScriptBlockRegistered("start"))
{
Page.RegisterClientScriptBlock("start",_start);
}
string _goScroll = "<script language="'javascript'">scrollTo("
+ this.HPos + ","+this.VPos+");</script>";
if(!Page.IsStartupScriptRegistered("goScroll"))
{
Page.RegisterStartupScript("goScroll",_goScroll);
}
}
}
}
I just want to say that I have stolen this idea from another one on the Web (I
don't remember who :( ) but I wasn't able to use it so I made my own code.
Mini Tip
- Don't forget to load it like a control.