维护Panel的滚动条ScrollBars位置(C#)-飞外

我们常将内容放在Panel中,例如文章,GridView控件等....。当内容超出Panel的高、宽时,可能就需要滚动条来进行控制。 当点击页面中按钮产生PostBack时,滚动条总是会回到最上面的位置,我们现在要解决的主要就是这个问题。

ScrollBar的可选项有:
成员名称
说明

Auto
根据需要,可显示水平滚动条、垂直滚动条或这两种滚动条。要不然也可以不显示任何滚动条。

Both
同时显示水平滚动条和垂直滚动条。

Horizontal
只显示水平滚动条。

None
不显示滚动条。

Vertical
只显示垂直滚动条。

演示如何控制ScrollBars的Demo,基本思路是通过两个HiddenField在Submit时纪录下Panel的scrollLeft,scrollTop的值,当IsPostBack时,当两个HiddenField的value重新设置给Panel的scrollLeft,scrllTop.

Html代码
在页面中放两个Panel,一个做为容器,一个做为内容(只为演示作用)。

...@ Page Language="C#" AutoEventWireup="true" CodeFile="ControlPanelScrollBarSample.aspx.cs" Inherits="ControlPanelScrollBarSample" %  !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"  html xmlns="http://www.w3.org/1999/xhtml"  head runat="server"  title 演示如何控制Panel的滚动块 /title  /head  body  form  runat="server"  div  asp:Panel ID="P_Container" runat="server" ScrollBars="Auto" Width="80%" Height="400px"  asp:Panel ID="P_Content" runat="server" Width="90%"  /asp:Panel  /asp:Panel  br /  asp:Button ID="BT_Submit" runat="server" Text="点击确发PostBack,查看滚动块的位置" /  /div  /form  /body  /html 
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/llxchen/archive/2008/01/31/2074979.aspx

//定义两个HiddenField,分别纪录Panel的ScrollBar的X与Y位置 HiddenField HF_ScrollPosX = new HiddenField(); HiddenField HF_ScrollPosY = new HiddenField(); HF_ScrollPosX.ID = "ScrollPosX"; HF_ScrollPosY.ID = "ScrollPosY"; form1.Controls.Add(HF_ScrollPosX); form1.Controls.Add(HF_ScrollPosY); //生成JS:将Panel的ScrollBar的X,Y位置设置给两个HiddenField string script; script = "window.document.getElementById('" + HF_ScrollPosX.ClientID + "').value = " + "window.document.getElementById('" + P_Container.ClientID + "').scrollLeft;" + "window.document.getElementById('" + HF_ScrollPosY.ClientID + "').value = " + "window.document.getElementById('" + P_Container.ClientID + "').scrollTop;"; this.ClientScript.RegisterOnSubmitStatement(this.GetType(), "SavePanelScroll", script); if (IsPostBack) //如果是PostBack,将保存在HiddenField的ScrollBar的X,Y值重设回给Panel的ScrollBar ...{ script = "window.document.getElementById('" + P_Container.ClientID + "').scrollLeft = " + "window.document.getElementById('" + HF_ScrollPosX.ClientID + "').value;" + "window.document.getElementById('" + P_Container.ClientID + "').scrollTop = " + "window.document.getElementById('" + HF_ScrollPosY.ClientID + "').value;"; this.ClientScript.RegisterStartupScript(this.GetType(), "SetPanelScroll", script, true); /**//// summary /// 填充内容数据,视情况可使外Panel产生滚动条即可 /// /summary private void FillContentPanel() ...{ Literal l = new Literal(); string context = ""; for (int i = 0; i 100; i++) ...{ context += " BR " + i + "行 中华人民共和国中华人民共和国!!!"; l.Text = context; P_Content.Controls.Add(l);本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/llxchen/archive/2008/01/31/2074979.aspx


我面加了UpdatePanel控件,演示没有效果,后来我没有加UpdatePanel这个控才会成功,这个问题,我在网上苦苦找了几个小时,最后这个才是最佳答案。

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/llxchen/archive/2008/01/31/2074979.aspx