[转载]固定(冻结)表头及首列DataGrid

本文介绍如何使用DataGrid实现类似于Excel的冻结效果,包括冻结表头和列。通过客户端和服务端两种方式锁定列,并提供简单方法固定表头。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

来源:codeproject  作者:David R Lewis

 查看更多精彩图片

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.

 

< script language = " javascript " >
            
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 "
                    } 
                } 
        
</ script >


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:
ExpandedBlockStart.gif ContractedBlock.gif Sub Item_Bound() Sub Item_Bound(ByVal sender As ObjectByVal e As DataGridItemEventArgs) _ 
InBlock.gif
Handles DataGrid1.ItemDataBound 
InBlock.gif    e.Item.Cells(
0).CssClass = "locked" 
InBlock.gif    e.Item.Cells(
1).CssClass = "locked" 
ExpandedBlockEnd.gif
End Sub

None.gif



另外单独固定表头,不固定列还有个简单的办法
把所有datagrid表格的Header做成类似Excel表格,当table中数据很多的时候,我们可以下拉滚动条,还能保持header固定。在网上搜索后找到了如下比较简单的方法。具体应用如下:
1. 在CSS 中添加一个Class
ExpandedBlockStart.gif ContractedBlock.gif .fixHeaderStyle  {dot.gif} {
InBlock.gif font-size
: 9pt;
InBlock.gif vertical-align
: middle;
InBlock.gif text-transform
: capitalize;
InBlock.gif font-family
: "Arial" , "Helvetica" , "sans-serif";
InBlock.gif height
: 25px;
InBlock.gif background-color
: #ecf4fe;
InBlock.gif text-align
: center;
InBlock.gif text-decoration
: none;
InBlock.gif POSITION
: relative;    --必要的
InBlock.gif TOP
: expression(this.offsetParent.scrollTop)  --必要的
ExpandedBlockEnd.gif
}

None.gif

在页面上,类似代码如:
< DIV  style ="OVERFLOW: auto; WIDTH: 100%; HEIGHT: 300px"  align ="center" >
 
< asp:DataGrid  id =grdCurRateVoy  runat ="server"  Width ="100%"    Visible ="True" >
 
< ItemStyle  CssClass ="ItemStyle" ></ ItemStyle >
 
< HeaderStyle  CssClass ="fixHeaderStyle" ></ HeaderStyle >
 
< PagerStyle  CssClass ="PagerStyle" ></ PagerStyle >
 
</ asp:DataGrid >
</ DIV >

转载于:https://www.cnblogs.com/Bruce_H21/archive/2006/11/04/549908.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值