The ASP.NET Panel controls loose their scroll bar position during a partial page update event. To maintain them, we currently need use additional JavaScript. There some good suggestions on the web of how to do it. Here I'd like to add a convenient way of embedding them into your code. If, for example, we have a Panel control with the MyPanel ID, we can add the following line to the .aspx file after our Panel:
<%# ScrollManager.Script(MyPanel)%>
To support this method call, we create a class that generates the required JavaScript script. Additionally, we could also add the script to the page programmatically using the RegistrClientScriptBlock call as it is shown below.
public static void Add(Panel c)
{
string script = Script(c);
ScriptManager.RegisterClientScriptBlock(c, typeof(Panel),
c.ClientID + "_ScrollManager", script, false);
}
Now, we just need to create the method for generating the JavaScript script for maintaining the scroll bar positions. Please see a possible way of doing it below. Kudos to Andrew Frederick for the JavaScript code, which I have modified. The method take the reference to our Panel control as a parameter because it needs to access the ClientID property of the Panel control. This allows finding the control in the JavaScript function below.
public static string Script(Control p)
{
string scrollLeftVarName = string.Format("{0}_scrollLeftPos", p.ClientID);
string scrollTopVarName = string.Format("{0}_scrollTopPos", p.ClientID);
string beginRequestHandlerName = string.Format("{0}_beginRequestHandler", p.ClientID);
string endRequestHandlerName = string.Format("{0}_endRequestHandler", p.ClientID);
return
"<script type='text/javascript'>" +
"var " + scrollLeftVarName + "," + scrollTopVarName + ";" +
"if(typeof(Sys) != 'undefined' && Sys != null)" +
"{" +
"var prm = Sys.WebForms.PageRequestManager.getInstance();" +
"prm.add_beginRequest(" + beginRequestHandlerName + ");" +
"prm.add_endRequest(" + endRequestHandlerName + ");" +
"}" +
"function " + beginRequestHandlerName + "(sender, args)" +
"{" +
"var c = $get('" + p.ClientID + "');" +
"if(typeof(c) != 'undefined' && c != null)" +
"{" +
scrollLeftVarName + " = c.scrollLeft;" +
scrollTopVarName + " = c.scrollTop;" +
"}" +
"}" +
"function " + endRequestHandlerName + "(sender, args)" +
"{" +
"var c = $get('" + p.ClientID + "');" +
"if(typeof(c) != 'undefined' && c != null)" +
"{" +
"c.scrollLeft = " + scrollLeftVarName + ";" +
"c.scrollTop = " + scrollTopVarName + ";" +
"}" +
"}" +
"</script>";
}
|