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

The Freeze Pane DataGrid

, 14 Nov 2004
Rate this:
Please Sign up or sign in to vote.
Creating a DataGrid with the ability to lock the header row and first column(s).

Sample Image

Introduction

During a recent project, I was asked to make the DataGrid behave like an Excel freeze pane. That’s right; freeze the header row and freeze the left column of a DataGrid. After several hours of searching for someone that has done this and posted the code, I gave up and tried to figure out a solution myself. The project source code above provides three ASPX files. One to lock the column(s) from the client side, one to lock the column(s) from the server side, and one to lock the column from the server side and then unlock/lock the column from the client side.

Background

The plan is actually fairly simple. While browsing the net for a solution, I found a great article on how to create a freeze pane from an HTML table. The solution is CSS based and only works with Internet Explorer, but does degrade well in other browsers. I would like to thank Brett Merkey for providing this solution. His ‘Lock or Freeze Columns with Non-scroll headers’ provided me with the idea and can be viewed here.

The solution is fairly simple, and in the end, you will have two different ways to lock the DataGrid columns.

Here is a synopsis of what we will be doing to create the freeze pane effect:

  • Creating a simple DataGrid with data surrounded by a <div> tag.
  • Modifying the DataGrid to render <th> tags inside the header row.
  • Creating a style sheet that will lock the DataGrid header row and column(s).
  • Locking the column(s) from the client side.
  • Locking the column(s) for the server side.

Using the code

Modifying the DataGrid to render <th> tags

The first problem that we run into is that the DataGrid does not render the <th> element but rather the common <td> element in the header. Luckily for us, Microsoft put out a rather obscure hotfix for this. Most of us have already downloaded this hotfix without knowing it. You can view more information (or download it if you have not done so yet) here.

Among other things, this hotfix adds the property UseAccessibleHeader to the DataGrid. This property, when set to true, ‘renders DataGrid table headers in <th> tags with a scope="col" attribute.’

The finished DataGrid code will look something like this:

<div id="div-datagrid">
<asp:DataGrid id="DataGrid1" runat="server" CssClass="Grid" UseAccessibleHeader="True">
    <AlternatingItemStyle CssClass="GridAltRow"></AlternatingItemStyle>
    <ItemStyle CssClass="GridRow"></ItemStyle>
    <Columns>
    <asp:BoundColumn DataField="Name" HeaderText="Name" 
        ItemStyle-Wrap="False"></asp:BoundColumn>
    <asp:BoundColumn DataField="Address" HeaderText="Address" 
        ItemStyle-Wrap="False"></asp:BoundColumn>
    <asp:BoundColumn DataField="City" HeaderText="City" 
        ItemStyle-Wrap="False"></asp:BoundColumn>
    <asp:BoundColumn DataField="State" HeaderText="State" 
        ItemStyle-Wrap="False"></asp:BoundColumn>
    <asp:BoundColumn DataField="Zip" HeaderText="Zip" 
        ItemStyle-Wrap="False"></asp:BoundColumn>
    <asp:BoundColumn DataField="Random Babble" 
        HeaderText="Random Babble" 
        ItemStyle-Wrap="False"></asp:BoundColumn>
    </Columns>
</asp:DataGrid>
</div>

Creating the style sheet

The style sheet is the key to this project. There are two things that need to be noted. First, CSS expressions are used. CSS expressions were introduced in Internet Explorer 5.0, and it allows you to assign a JavaScript expression to a CSS property. In this case, we are setting the horizontal and vertical scrolling position of the document elements by using expressions. Second, there is a certain order in which the styles need to be set. If you change the order of the styles listed below, you will come up with some rather odd results. And in case you’re wondering… yes I went through almost every incorrect order before actually coming up with an order that works.

Here is the CSS code:

/* Div container to wrap the datagrid */
div#div-datagrid {
width: 420px;
height: 200px;
overflow: auto;
scrollbar-base-color:#ffeaff;
}

/* Locks the left column */
td.locked, th.locked {
font-size: 14px;
font-weight: bold;
text-align: center;
background-color: navy;
color: white;
border-right: 1px solid silver;
position:relative;
cursor: default;
/*IE5+ only*/
left: expression(document.getElementById("div-datagrid").scrollLeft-2);
}

/* Locks table header */
th {
font-size: 14px;
font-weight: bold;
text-align: center;
background-color: navy;
color: white;
border-right: 1px solid silver;
position:relative;
cursor: default;
/*IE5+ only*/
top: expression(document.getElementById("div-datagrid").scrollTop-2);
z-index: 10;
}

/* Keeps the header as the top most item. Important for top left item*/
th.locked {z-index: 99;}

/* DataGrid Item and AlternatingItem Style*/
.GridRow {font-size: 10pt; color: black; font-family: Arial; 
             background-color:#ffffff; height:35px;}
.GridAltRow {font-size: 10pt; color: black; font-family: Arial; 
             background-color:#eeeeee; height:35px;}

Locking the column(s) from the client side

In order to lock the column from the client side, we just need to create a script that changes the style of the first column to ‘locked’. Multiple columns can be frozen just by modifying the code below. The following script is added to the head of the ASPX file to lock the first column.

function lockCol(tblID) {
  var table = document.getElementById(tblID);
  var button = document.getElementById('toggle');
  var cTR = table.getElementsByTagName('tr');  //collection of rows

  if (table.rows[0].cells[0].className == '') {
    for (i = 0; i < cTR.length; i++)
    {
    var tr = cTR.item(i);
    tr.cells[0].className = 'locked'
    }
    button.innerText = "Unlock First Column";
  } else {
    for (i = 0; i < cTR.length; i++)
        {
    var tr = cTR.item(i);
    tr.cells[0].className = ''
    }
    button.innerText = "Lock First Column";
  }
}

Locking the column(s) from the server side

Again, in order to lock the column from the server side, we just need to change the style of the first column to ‘locked’. In order to implement this, we use the ItemDataBound method of the DataGrid. The following code sets the style of the first column to ‘locked’. This is actually extremely simple with the code below:

Sub Item_Bound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) _
Handles DataGrid1.ItemDataBound
    e.Item.Cells(0).CssClass = "locked"
End Sub

And to freeze the first two columns, it's just as easy:

Sub Item_Bound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) _
Handles DataGrid1.ItemDataBound
    e.Item.Cells(0).CssClass = "locked"
    e.Item.Cells(1).CssClass = "locked"
End Sub

License

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

Share

About the Author

David R Lewis
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
GeneralNice article PinmemberBinu198523-Jul-14 23:52 
QuestionLeft: expression is not working in my code can you please help me urgent PinmemberSri Kiran21-Oct-13 2:02 
GeneralMy vote of 5 Pinmemberprashant patil 49878-May-13 1:59 
Questionihi Pinmemberprashant patil 49878-May-13 1:58 
Questionihi Pinmemberprashant patil 49878-May-13 1:58 
QuestionProblem with freezing 3 columns Pinmember12324r3235329-Jul-12 12:42 
Questionexample code that runs GridView and IE 8 Pinmemberjovino balunan14-Oct-11 21:46 
QuestionFreeze Pane datagrid is not working in Firefox Pinmemberranjithkutti9-Sep-11 19:34 
QuestionChrome/FireFox/Safari Pinmemberroggen1820-Jul-11 6:05 
GeneralMy vote of 1 Pinmembershankar4sai8-Nov-10 23:30 
GeneralMy vote of 2 PinmemberAMIT_BHAGAT20-Aug-10 2:16 
GeneralFreezed Header and Footer Pinmembershahib17-Aug-10 5:55 
Questionfreeze header problem Pinmemberschauhan1311-Aug-10 6:32 
AnswerRe: freeze header problem PinmemberAMIT_BHAGAT20-Aug-10 2:12 
Generalfreezing column in gridview Pinmembermanasa29114-Mar-10 23:28 
Questionwill this code give the same result if we set AutoGernerateColumn=true? [modified] PinmemberKhushbu Patel7-Oct-09 2:12 
GeneralPerfomance problem freezing columns and header for a big grid view Pinmembersingini30-Sep-09 22:33 
QuestionDoes not work for Opera or Firefox... Pinmemberarecev16-Sep-09 6:13 
AnswerRe: Does not work for Opera or Firefox... PinmemberGavin.Yim20-Dec-09 19:52 
GeneralRe: Does not work for Opera or Firefox... PinmemberRDurando2-Jun-10 21:10 
GeneralPerformance problems roblems freezing header on large datagrids Pinmemberckheisler5-Jun-09 12:37 
QuestionFrozen columns PinmemberHpadmasola6-Feb-09 6:12 
Generalproblem using drop down and in some other places PinmemberNidhiKanu4-Feb-09 2:56 
GeneralFreeze pane column PinmemberNidhiKanu28-Jan-09 21:31 
GeneralExcellent solution Pinmemberdkirschman10-Oct-08 8:18 
QuestionThis is not working with gridview [modified] PinmemberMurali Manohar Pareek25-Sep-08 23:12 
AnswerRe: This is not working with gridview Pinmemberdkirschman10-Oct-08 8:30 
QuestionRe: This is not working with gridview Pinmembergannamalai11-Nov-08 3:51 
Questionperformance degredation with freezing columns in large gridviews PinmemberAnkur Juneja25-Jun-08 0:50 
GeneralFreeze column, im trying this code on GridView /Template field in VS 2008 PinmemberAl-jaberi16-Jun-08 4:01 
Generalperformance degredation with freezing columns in large gridviews - solved [modified] Pinmemberchuck.rostance10-Apr-08 5:21 
GeneralRe: performance degredation with freezing columns in large gridviews - solved [modified] Pinmembernickyt26-May-08 9:52 
GeneralRe: performance degredation with freezing columns in large gridviews - solved Pinmemberpun.agarwal28-Jul-08 0:22 
GeneralRe: performance degredation with freezing columns in large gridviews - solved Pinmembernickyt28-Jul-08 3:08 
GeneralRe: performance degredation with freezing columns in large gridviews - solved Pinmemberpun.agarwal29-Jul-08 0:19 
GeneralRe: performance degredation with freezing columns in large gridviews - solved Pinmemberpun.agarwal5-Aug-08 22:32 
GeneralRe: performance degredation with freezing columns in large gridviews - solved Pinmembermaybee9-Sep-08 17:30 
GeneralRe: performance degredation with freezing columns in large gridviews - solved Pinmembersamvanoye3-Jun-08 15:23 
QuestionHow to Print table headers on every page? Pinmemberhialmeyd8-Apr-08 15:50 
QuestionHow to use this for GridView PinmemberKhushi20053-Apr-08 6:12 
AnswerRe: How to use this for GridView Pinmemberbartfusers25-Aug-09 23:53 
GeneralGridView Fixed Header dropdown problem Pinmembermgr_2k718-Nov-07 18:34 
QuestionRe: GridView Fixed Header dropdown problem Pinmemberolatz16-Apr-08 22:01 
GeneralRe: GridView Fixed Header dropdown problem Pinmembermgr_2k716-Apr-08 22:12 
GeneralRe: GridView Fixed Header dropdown problem Pinmemberolatz16-Apr-08 22:29 
GeneralRe: GridView Fixed Header dropdown problem Pinmemberolatz16-Apr-08 22:31 
GeneralRe: GridView Fixed Header dropdown problem Pinmembermgr_2k716-Apr-08 23:25 
GeneralRe: GridView Fixed Header dropdown problem Pinmemberolatz16-Apr-08 23:41 
GeneralRe: GridView Fixed Header dropdown problem Pinmembermgr_2k716-Apr-08 23:57 
GeneralThank you for the code Pinmemberjpt4u2c8-Oct-07 23:56 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 14 Nov 2004
Article Copyright 2004 by David R Lewis
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid