Click here to Skip to main content
15,881,173 members
Articles / Web Development / ASP.NET
Article

Reset the page scroll position after a PostBack

Rate me:
Please Sign up or sign in to vote.
4.18/5 (10 votes)
31 Aug 2003 251K   1.5K   60   42
Reset the page scroll position after a PostBack using a custom class derived from HtmlInputHidden

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

C#
 using System;
 using System.Web.UI;

 namespace AnnulMvtPostBack
 {
  
  public class GetPositionPostBack: 
    System.Web.UI.HtmlControls.HtmlInputHidden, 
    IPostBackDataHandler
  {
    //The position is saving in the viewstate.
    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; }
    }
    
    //Here the value of the HiddenControl is catching 
    //before the PostBack
    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; //return true to execute RaisePostDataChangedEvent();
      }

      //_______return_________

      if(_returnV || _returnH) return false; 
       //return true to execute RaisePostDataChangedEvent();
      else return false;    
    }
    
    //This function is here just to understand the LoadPostData 
    //with the RaisePostDataChangedEvent() 
    public void RaisePostDataChangedEvent() 
    {
      // Part of the IPostBackDataHandler contract.  Invoked 
      // if we ever returned true from the
      // LoadPostData method (indicates that we want a change 
      // notification raised).  Since we
      // always return false, this method is just a no-op.
      
    }    

    //The control is rendered with a UniqueId and Javascript Code 
    //is use to get the position of the scrollbar
    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);
      }
      //_______________Move the scrollbar____________________________________
      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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
France France
Young developer C#, Javascript, and database but just for fun...

Comments and Discussions

 
QuestionRetain scroll position after postback Pin
Sharad CG15-Nov-10 22:16
Sharad CG15-Nov-10 22:16 
Generalasp.net 2 provides easier way Pin
Mark Adamson25-Sep-06 4:11
Mark Adamson25-Sep-06 4:11 
GeneralRe: asp.net 2 provides easier way Pin
dB.22-Apr-07 8:31
dB.22-Apr-07 8:31 
GeneralRe: asp.net 2 provides easier way Pin
snehasish25-Sep-08 22:04
snehasish25-Sep-08 22:04 
GeneralMore &quot;compliant&quot; code [modified] Pin
nezza17-Aug-06 4:33
nezza17-Aug-06 4:33 
GeneralQuestions for implementing code... Pin
Something Witty10-Mar-06 5:34
Something Witty10-Mar-06 5:34 
GeneralRe: Questions for implementing code... Pin
WebGourou11-Mar-06 9:25
WebGourou11-Mar-06 9:25 
GeneralA small suggestion Pin
moredip8-Jan-05 6:41
moredip8-Jan-05 6:41 
QuestionHow to use? Pin
LittleVexy7-Mar-04 5:18
LittleVexy7-Mar-04 5:18 
AnswerHow to get it to Work... Pin
LittleVexy7-Mar-04 5:51
LittleVexy7-Mar-04 5:51 
GeneralRe: How to get it to Work... Pin
LittleVexy7-Mar-04 5:54
LittleVexy7-Mar-04 5:54 
GeneralEasier way is to set SmartNavigation=true Pin
kamalM10-Sep-03 20:29
kamalM10-Sep-03 20:29 
GeneralRe: Easier way is to set SmartNavigation=true Pin
WebGourou11-Sep-03 4:55
WebGourou11-Sep-03 4:55 
GeneralRe: Easier way is to set SmartNavigation=true Pin
Zencat19-Aug-04 11:06
Zencat19-Aug-04 11:06 
GeneralRe: Easier way is to set SmartNavigation=true Pin
Fallen-Angel12-Aug-04 6:23
Fallen-Angel12-Aug-04 6:23 
GeneralRe: Easier way is to set SmartNavigation=true Pin
Staring at the Sun12-Jan-05 12:14
Staring at the Sun12-Jan-05 12:14 
GeneralOriginal Pin
Cypher3-Sep-03 3:28
Cypher3-Sep-03 3:28 
GeneralRe: Original Pin
bobjeey3-Sep-03 22:52
bobjeey3-Sep-03 22:52 
GeneralRe: Original Pin
bobjeey4-Sep-03 1:04
bobjeey4-Sep-03 1:04 
GeneralRe: Original Pin
Cypher4-Sep-03 2:27
Cypher4-Sep-03 2:27 
GeneralRe: Original Pin
WebGourou4-Sep-03 9:20
WebGourou4-Sep-03 9:20 
GeneralRe: Original Pin
min.dom7-Sep-03 23:30
min.dom7-Sep-03 23:30 
GeneralRe: Original Pin
WebGourou8-Sep-03 7:05
WebGourou8-Sep-03 7:05 
GeneralRe: Original Pin
BillBelliveau9-Sep-03 13:19
BillBelliveau9-Sep-03 13:19 
GeneralRe: Original Pin
min.dom9-Sep-03 15:27
min.dom9-Sep-03 15:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.