以前在做GridView添加合计行时,都是通过DataTable新建一行,然后把数据写进去,最后绑定到GridView中,虽然功能实现了,但是不能很好的控制它的样式,某些时候还会出现问题,如:GridView中包含模板列,模板列又绑定了按钮控件,这样的话绑定到GridView中,合计行那行中按钮也会显示出来,这样就会十分的不友好。本文将演示如何使用GridView自带的Footer(脚注行)来解决这一问题,并且还可以随心所欲的控制其样式。
OnRowDataBound 事件
decimal totalCol8 =0.00M, totalCol9 = 0.00M, totalCol10 = 0.00M;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView row = (DataRowView)e.Row.DataItem;
totalCol8 += Convert.ToDecimal(row[9].ToString());
totalCol9 += Convert.ToDecimal(row[10].ToString());
totalCol10 += Convert.ToDecimal(row[11].ToString());
}
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = "合计";
e.Row.Cells[8].Text = totalCol8.ToString();
e.Row.Cells[9].Text = totalCol9.ToString();
e.Row.Cells[10].Text = totalCol10.ToString();
e.Row.CssClass = "cssFooter"; //设置行的样式
}
}
样式文件:
<style type="text/css" >
.cssFooter
{
background-color:white;
color:black;
font-size:12px;
font-family:Arial;
}
</style>
设置GridView显示脚注行(Footer)
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False"
showfooter="true" --显示脚注
onRowDataBound="GridView1_RowDataBound"> --在事件中处理行的合计任务
if (e.Row.RowType == DataControlRowType.Footer)
{
//以跨栏的方式合并单元格
e.Row.Cells[0].ColumnSpan = 8;
//隐藏除第一个单元格之后的所有单元格
for (int index = 1; index <= e.Row.Cells.Count - 1; index++)
{
e.Row.Cells[index].Visible = false;
}
e.Row.Cells[0].Text = "章立民研究室制作" + DateTime.Now.ToString("yyyy-MM-dd");
e.Row.Cells[0].CssClass = "cssFooter";
}
样式代码:
.cssFooter
{
background-image:url(images/back_img.gif);
font: italic 25px SimHei,标楷体,黑体;
text-align:right;
color:blue;
height:90px;
}