Click here to Skip to main content
Click here to Skip to main content

Maintain GridView Scroll Position and Header Inside UpdatePanel

By , 18 Oct 2008
 

LastTry.gif

Introduction

For most kind of web development, we mostly need to show data inside a GridView. Suppose we need to show 500 records inside a GridView and when the user selects a record, the details are displayed in the bottom or any where else in the page. Now for preventing postback for such operations, generally we use the AJAX UpdatePanel and put the GridView inside the UpdatePanel. This will resolve the problem of postback, but then what happens? When you want to check record 100, you just scroll down the records and select the record for checking the details, and now you get the records inside your details area, but look at the GridView scroll position. Ohhhh...no, it should not be happening: it is back at the top of the records. We have to now solve this problem at the time of partial postback of the page.

Problem Statement

Here I am going to describe the actual problem in detail:

Problem State Description

ajax.h1.jpg

I have a GridView with a scroll bar where I have 8 records. I can see 5 records at a time. For getting the other records, I have to scroll down. I just select the first records and get the details in the details area.

ajax.h2.jpg

No I want to see some other records. Let's say the 8th record. I just scroll down the scroll bar but I don't select a record. Now check the scroll bar position and the student detail.

ajax.h3.jpg

Now I select the 8th record. You will see in the details section that the detail of that records is showing, but check the scroll bar position.

This is quite a frustrating scenario for the user. We have a good solution for that by handling the partial post back of the page.

The Solution

When we are using an UpdatePanel, we need more control on the UpdatePanel to solve this problem. For that, we need to use the Sys.WebForms.PageRequestManager class. This is used to manage the partial-page update by using client-side script. We do not need to create an object of the PageRequestManager class directly. For this solution, I have used two events. beginRequest is raised before processing of the asynchronous postback starts. Here I have just retrieved the Div position of the scroll and stored it in a variable. endRequest is raised after an asynchronous postback is finished and control has been returned to the browser. Here I have just assigned the retrieved scroll position to the div again. For more info, click here.

Using the Code

I have written the following JavaScript code for handling the partial postback, which handles the Div scroll position during the postback of the GridView inside the UpdatePanel:

<script language="javascript" type="text/javascript">
// This Script is used to maintain Grid Scroll on Partial Postback
var scrollTop;
//Register Begin Request and End Request 
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
//Get The Div Scroll Position
Function BeginRequestHandler(sender, args) 
{
var m = document.getElementById('divGrid');
scrollTop=m.scrollTop;
}
//Set The Div Scroll Position
function EndRequestHandler(sender, args)
{
var m = document.getElementById('divGrid');
m.scrollTop = scrollTop;
} 
</script>

Following is the code for the GridView. The Gridview should be placed inside an UpdatePanel and a Div control. The Div allow us to scroll the GridView.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="divGrid" style="overflow: auto; height: 130px"> 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" Width="235px"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<HeaderStyle CssClass="HeaderFreez" />
<Columns>
<asp:BoundField DataField="Roll" HeaderText="Roll" SortExpression="Roll" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Langauge" HeaderText="Language" SortExpression="Langauge" />
<asp:CommandField ShowSelectButton="True" />
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:DotNetRnDDBConnectionString %>"
SelectCommand="SELECT * FROM [StudDetails]"></asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>

Here is the CSS code which is used to freeze the Header of the GridView. Just add this class as a HeaderStyle class of the Gridview. This will freeze the grid's header. We can use it in other cases where we need to freeze the header.

.HeaderFreez
{
   position:relative ;
   top:expression(this.offsetParent.scrollTop);
   z-index: 10;
}

Reference

History

  • Written on 17-Oct-2008.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Abhijit Jana
Software Developer (Senior)
India India
.NET Consultant | Former Microsoft MVP - ASP.NET | CodeProject MVP, Mentor, Insiders| Technology Evangelist | Author | Speaker | Geek | Blogger | Husband
 
Blog : http://abhijitjana.net
Web Site : http://dailydotnettips.com
Twitter : @AbhijitJana
My Kinect Book : Kinect for Windows SDK Programming Guide
Follow on   Twitter

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionGridView Controlmemberibrahim_540326-Feb-13 19:41 
Hello,
I have read "Maintain GridView Scroll Position and Header Inside UpdatePanel" Thanks for such nice article.
 
I have a project, and I want fixed two row and one column in Gridview. How????? Pls help me.....
QuestionAbt CodememberAmitDhakre13-Jul-12 1:36 
This was indeed helpful
But in JS function, function should have small F
Rectify it. It took an hour for me to see the prob
QuestionI am not using select button?membershuvra24-Apr-12 5:19 
I am not using select button in grid.. instead I am using mouse click to select the whole row.
 
the following code:
protected override void Render(HtmlTextWriter writer)
        {
            // .NET will refuse to accept "unknown" postbacks for security reasons.
            // Because of this we have to register all possible callbacks
            // This must be done in Render, hence the override
            for (int i = 0; i < GV_ModelList.Rows.Count; i++)
            {
                Page.ClientScript.RegisterForEventValidation(new System.Web.UI.PostBackOptions(GV_ModelList, "Select$" + i.ToString()));
            }
            // Do the standard rendering stuff
            base.Render(writer);
        }
 
and Grid_RowCreated function i add following function:
 
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GV_ModelList, "Select$" + e.Row.RowIndex);
 
but not your code is not working..How can i get Grid position in code behind?
AnswerRe: I am not using select button?membershuvra24-Apr-12 5:30 
It works..I change your code:
$(document).ready(function()
        {
            Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
        });
 
I call pagerequestmanager then page in read.. thanks you very much. its a great solution... cheer
shuvra
QuestionFix header doesnt work for me BUT YOUR POST IS MY MISSING LINK. Thanks so much!memberdonPEPOT3-Aug-11 23:35 
I used this to freeze my header.   Put this inside the BeginRequestHandler() and EndRequestHandler().
 
$("#" + '<%= gv_ProjectCalendar.ClientID %>').fixer({
                        fixedrows: 1, fixedcols: 2, width: 0,
                        height: ($("#" + '<%= gv_ProjectCalendar.ClientID %>').height() > 400) ? 400 : $("#" + '<%= gv_ProjectCalendar.ClientID %>').height()});              
 
You might also want to put this in head for on_load:
<script type="text/javascript">
            $(document).ready(function () {
                  $("#" + '<%= gv_ProjectCalendar.ClientID %>').fixer({
                        fixedrows: 1, fixedcols: 2, width: 0,
                        height: ($("#" + '<%= gv_ProjectCalendar.ClientID %>').height() > 400) ? 400 : $("#" + '<%= gv_ProjectCalendar.ClientID %>').height()
                  }); });
      </script>
General5 is my VotememberHernan K. Cabrera29-Jul-11 22:53 
Work Perfectly...
 
Thanks a lot.
GeneralMy vote of 5memberRashmi_Karnam17-May-11 0:42 
Solved problem with less effort. Also supports all browsers.
GeneralMy vote of 5memberSChristmas15-Feb-11 0:59 
Cool stuff
GeneralHeaderFreeze is NOT working in IE8, Mozilla and ChromememberAnurag Gandhi3-Dec-09 3:46 
Hi Abhijit,
Its nice to see your article, but Header is not Freezed in IE8, Mozilla and Chrome.
Its working fine in IE8 compatibility view.
 
Could you please suggest something on this?
 
Overall its a nice article and You still got my 5. Thumbs Up | :thumbsup:
 
Anurag Gandhi.
http://www.gandhisoft.com
Life is a computer program and every one is the programmer of his own life.

GeneralRe: HeaderFreeze is NOT working in IE8, Mozilla and ChromemvpAbhijit Jana3-Dec-09 21:40 
Hi Anurag,
Thanks for your vote and comments !!
 
Sorry, I have tested it on IE and FF . It was working fine . Let me try with other browser.
 
Thanks for letting me know !!
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.

GeneralRe: HeaderFreeze is NOT working in IE8, Mozilla and Chromememberjoshshrf4-Dec-09 6:29 
I just found your article yesterday and am having the same issue with IE8.
 
I found this article on MS about it http://msdn.microsoft.com/en-us/library/ms537634(VS.85).aspx[^]
 
It seems to be that using the expression method was deprecated from IE8 due to CSS 2.1 compatibility.
 
I'm trying to find the best workaround myself as this functionality is much needed in our application.
GeneralRe: HeaderFreeze is NOT working in IE8, Mozilla and ChromememberAbhi-now10-Mar-10 2:36 
Just wanted to let you know .. I tried this on IE 8 and it works just fine.
 
FYI: All I used is the CSS class on my existing code. Exactly what I was looking for. Thanks! Big Grin | :-D
GeneralRe: HeaderFreeze is NOT working in IE8, Mozilla and ChromemvpAbhijit Jana13-Jun-10 21:10 
Great !
Cheers !
Abhijit Jana | MVP
Web Site : abhijitjana.net | Follow Me @ twitter
Read my Latest Article :Mastering Debugging in VS 2010

GeneralRe: HeaderFreeze is NOT working in IE8, Mozilla and Chromememberkumargtl28-Apr-11 2:41 
Hi Abhijit,
 
I checked your solution but could not able to get it as said.
 
I am using a user control inside user control using updatepanel, in content, aspwizard control was used,the gridview was placed in asp:panel control. In a new page when using this usercontrol not able to fix the gridview scroll position using this code.
 
Any idea.?
 
Usercontrol
-->updatepanel
--->aspwizard control
---->asp panel
----->gridview.
 
Now where to place the javascript code, in usercontrol page or in independent page.pls let me know,
 
thanks in advance.
GeneralRe: HeaderFreeze is NOT working in IE8, Mozilla and ChromememberdonPEPOT3-Aug-11 23:18 
Yes! The expression() was already deprecated and Visual Studio treat this as invalid values. But you can still use it.
 
For VS 2010 :
Just uncheck the Tools>Options>TextEditor>CSS>Miscellaneous>Detect invalid values.
 
I think for VS 2005:
Tools>Options>TextEditor>CSS>CSS Specific>Detect invalid values.
GeneralRe: HeaderFreeze is NOT working in IE8, Mozilla and ChromememberVince3rd24-Oct-11 22:52 
Microsoft JScript runtime error: Object required on scrollTop = b1.scrollTop;
thanks....
GeneralLost the Headermemberlqluo19-Nov-09 22:44 
That's something!
But when I used it in my solition with the Master page, click the "select" I lost the Header. can you help me?
Thanks a lot!
PS:when on top of the scoll, it have the header, otherwise, it lost. why? and
In some case it will not only one scoll on the page.
GeneralRe: Lost the HeadermvpAbhijit Jana19-Nov-09 22:48 
Thanks for reading my article . Which Browser are you using ?
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.

GeneralRe: Lost the Headermemberlqluo19-Nov-09 22:53 
IE7
GeneralRe: Lost the HeadermvpAbhijit Jana19-Nov-09 23:01 
lqluo wrote:
IE7

It should not. D'Oh! | :doh: Have you tired with the attached application with this article ?
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.

GeneralRe: Lost the Header [modified]memberlqluo22-Nov-09 20:49 
I just run the attached application, It's seem to well. but could you add the master page and see the result?
 
Confused | :confused: I still lost the header on it!!!
 
PS:I'm sorry to reply you so later
 
modified on Monday, November 23, 2009 3:21 AM

GeneralVery useful codememberSivaPrakasamDotNet28-Oct-09 22:57 
Thank you. Your example helped me a lot.
GeneralRe: Very useful codemvpAbhijit Jana7-Nov-09 1:37 
Nice to know it helped you ! Smile | :)
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.

GeneralThanksmembermilindchavan1216-Oct-09 1:44 
Really great work Abhijit
GeneralRe: ThanksmvpAbhijit Jana16-Oct-09 2:09 
Nice to know you liked it ! Thumbs Up | :thumbsup:
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 18 Oct 2008
Article Copyright 2008 by Abhijit Jana
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid