using
System;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
![None.gif](/Images/OutliningIndicators/None.gif)
namespace
PageGrid
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
public class GridPager
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
int _pageSize;
string _header;
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 传入DataGrid的引用和每页记录数,让DataGrid在打印时分页显示
/// </summary>
/// <param name="grid">被搞的DataGrid</param>
/// <param name="pageSize">每页显示记录条数</param>
public GridPager(System.Web.UI.WebControls.DataGrid grid, int pageSize)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
_pageSize = pageSize;
grid.ItemDataBound += new DataGridItemEventHandler(grid_ItemDataBound);
grid.ItemCreated += new DataGridItemEventHandler(grid_ItemCreated);
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
private void grid_ItemDataBound(object sender, DataGridItemEventArgs e)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if (e.Item.ItemIndex > 0 && e.Item.ItemIndex % _pageSize == 0)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
LiteralControl l = new LiteralControl();
//把表头代码结尾的</td>\r\n</tr>截去
string header = _header.Remove(_header.Length - 12, 12);
//加上处理过的表头
l.Text = "</td></tr><tr><td bordercolor=white cellpadding=0 style=\"page-break-after:always\" colspan=\"" + e.Item.Cells.Count + "\"></td></tr><td colspan=" + + e.Item.Cells.Count + "\"></td>" + header;
//如果最后一列是template column得用这句加,注释下面的.原因不明...
//e.Item.Cells[e.Item.Cells.Count-1].Controls.Add(l);
e.Item.Cells[e.Item.Cells.Count-1].Text += l.Text ;
}
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
private void grid_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{ //拿到表头的html代码
if (e.Item.ItemIndex == -1)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(tw);
e.Item.RenderControl(htw);
_header = tw.ToString();
}
}
}
}
通过在ItemDataBound事件里判断是第几条记录.如果能被PageSize整除,就往最后一个TableCell里加上一个LiteralControl,里面带有一个有打印换页标记(
page-break
-
after:always
)的td和DataGrid的表头.这样出来的DataGrid就能分页打印了.遗憾的是,每页最顶和最底的垂直两边都会有两个象素突出来
如果用Repeater搞的话就可以做的很漂亮了.table不要显示border,而是通过写td的style来显示线框,这样分页处td的边框就不会显示出来了.有点麻烦
http://files.cnblogs.com/Yok/PageGrid.zip