![]() |
Products Downloads Blog Forum Articles Contact |
| Articles |
ASP.Net 2.0: Maintaining a GridView Scroll Position after Postback when Using a Panel
The Issue MaintainScrollPositionOnPostback="true" works great for maintaining a GridView's scroll position if it is sitting all by its lonesome on a page. If you are listing a large amount of data and select a row, the browser's scrollbar position (and therefore the GridView's position) is neatly placed where it should be after the postback. But this approach introduces a number of usability issues. If your GridView is long and your application has commands to act on a selected row, say to turn the background color green when you select a row and use a "turn green" menu item at the top of your page, you force the user to go through a scroll to item in grid -> select -> scroll up to top of page to execute menu command drill. To remedy this you discover that placing the GridView in a Panel control works neatly... the user can scroll to an item in your GridView and select it without scrolling the entire page itself. Great! That is, until you further discover that MaintainScrollPositionOnPostback doesn't work on the GridView when it is embedded in a Panel. What to do?
The Solution In ASP.Net 2.0 you only need to do two things... save off the ClientID for the selected row in a session varibale, and add a few lines of JavaScript to get it working. Step One: Store the Row's ClientID ASP.Net 2.0 dutifully assigns a ClientID to each row in the GridView. As an aside, from my research it appeared that the old DataGrid required that this be done programatically, so that sent me on a number of wild goose chases. In your _SelectedIndexChanged event, assign the row's ClientID to a session variable:
Step Two: Insert Some JavaScript to Scroll to the Correct Row Following a PostBack In your code-behind file in the <asp:Content> section, paste the following code right before the ending </asp:Content> tag:
That's it... your GridView's selected row will now appear at the top of the Panel after the PostBack. If you have any comments on the above, feel free to post them in the forum. I hope this helps... much headbanging was involved arriving at these two simple steps to get it working and I hope I can save others some frustration!
|
||