Wednesday, July 08, 2009

Maintain scroll position for Listbox ASP.NET

I was facing a problem with maintaining scroll position for a list box inside a update panel in ASP.NET.
So I tried o Google the problem and found no convincing answers.
Finally I got it working by a small JavaScript method that was called at end request handler for any AJAX calls for the page.
The JavaScript is as follows:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
// reseting the all selected indices again for multi selection or single selection in the reverse order
// inorder to get the scroll postion at the top of first selection
var lstBoxLen = document.getElementById(lstEmployees).length;
for (var i = lstBoxLen - 1; i >= 0; i--) {
if (document.getElementById(lstEmployees).options[i].selected) {
document.getElementById(lstEmployees).options[i].selected = true;
}
}

}
This solution is now working for both single selection and multi selection based list box.
I would appreciate any other better way of doing this.

May be this will be helpful to some one who is finding it difficult to restore scroll position of list box after auto post back.

No comments: