views:

3233

answers:

2

I have a listbox inside an update panel. When I scroll down and select an item, it scrolls back to the top of the listbox. I heard that the dom does not keep track of the scroll position on a postback. Does anyone have a solution/example on how to solve this?

Thanks, XaiSoft

+4  A: 

You're running into this problem because the UpdatePanel completely replaces your scrolled <select> element with a new one when the asynchronous request comes back.

Possible solutions:

  1. Use JavaScript to store the scrollTop property of the <select> element in a hidden form element before the UpdatePanel is submitted (by calling the ClientScriptManager.RegisterOnSubmitStatement method) and then setting it on the new <select> when the AJAX call comes back. This will be tedious, error-prone, and probably not very compatible (see here).

  2. Use JavaScript to store the <select>'s selectedIndex property and re-select that item when the AJAX call comes back. Obviously this won't work if the user hasn't selected anything yet.

  3. Don't use UpdatePanels. Try jQuery + ASP.NET page methods instead.

Chris Zwiryk
I found this solution and it actually worked.http://basgun.wordpress.com/2008/06/09/maintain-scroll-position-updatepanel-postback/
Xaisoft
Good. It sounds like there's a problem with selectTop on IE6. The first comment on this page explains how you can get around it: http://geekswithblogs.net/lorint/archive/2005/12/16/63289.aspx
Chris Zwiryk
A: 

It seems that the following code example scrolls in the following way:

  • Internet Explorer 8: After postback the selected item is the first visible item.

  • Firefox: After postback the selected item is always visible (but might be the last visible item).

  • Chrome: After postback, the selected item might be hidden since the listbox scrolls to the top, as you say.

<asp:UpdatePanel ID="up1" runat="server">
    <ContentTemplate>
        <asp:ListBox ID="lb1" runat="server" Height="100px" AutoPostBack="true">
            <asp:ListItem>A</asp:ListItem>
            <asp:ListItem>B</asp:ListItem>
            <asp:ListItem>C</asp:ListItem>
            <asp:ListItem>D</asp:ListItem>
            <asp:ListItem>E</asp:ListItem>
            <asp:ListItem>F</asp:ListItem>
            <asp:ListItem>G</asp:ListItem>
            <asp:ListItem>H</asp:ListItem>
        </asp:ListBox>
    </ContentTemplate>
</asp:UpdatePanel>
Ole Lynge
Firefox scrolls to the top unpredictably for selected items. At first, I thought it might be because of the number of items in the listbox, but when select a particular item... sometimes it stays visible after a postback, and sometimes firefox scrolls to the top instead. The list isn't being rebuilt and the same thing happened when any item is clicked, so it's clearly a firefox bug, and it's still present as of version 3.0.13.
Triynko