Listbox Scrolling to Top on autopostback
Why 开发者_StackOverflow社区does asp.net listbox always scroll to top upon selecting an item when autopostback is on? How can I prevent this from happening?
I added the following jquery in javascript to fix the issue. I cannot remember where I found the solution but here it is. Just add the location of your target control - $get('YourDiv_YourPanel').
<script type="text/javascript">
//Maintain scroll position in given element or control
var xInputPanel, yInputPanel;
var xProductPanel, yProductPanel;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
yInputPanel = $get('MainContent_InputPanel').scrollTop;
yProductPanel = $get('MainContent_ProductPanel').scrollTop;
}
function EndRequestHandler(sender, args) {
$get('MainContent_InputPanel').scrollTop = yInputPanel;
$get('MainContent_ProductPanel').scrollTop = yProductPanel;
}
</script>
I had the same issue, and I figured out a way to do it with update panels. I believe it's due to the listbox being updated on postback, so update panels can help us make sure it doesn't update. Make sure the listbox is inside a conditional update panel with children as triggers set to 'false':
<asp:UpdatePanel runat="server" ID="updtpnlSearchResults" UpdateMode="Conditional" ChildrenAsTriggers="false">
Now put whatever needs to be changed when the list box selection changes inside an update panel of its own. That way the listbox doesn't get refreshed.
You need this page directive:
<%@ Page MaintainScrollPositionOnPostback="true" ... %>
You have a couple of options. You can either set MaintainScrollPositionOnPostBack to true in the page directive, or you can put the listbox in an update panel and use AJAX to maintain scroll position.
Page directive option:
<pages maintainScrollPositionOnPostBack="true" />
Update panel option:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:ListBox ID="ListBox1" runat="server" ...>
</ContentTemplate>
</asp:UpdatePanel>
精彩评论