首先:在GridView 属性设置中,ShowFooter 设为 true
方法一:使用SQL查询统计出合计值,在绑定GridView时让其结果赋于一个DataTable(全局变量),然后在RowDataBound事件中
其中dtSum是那个全局DataTable,在绑定GridView同时将SQL查询的结果赋给它;效果如下:
方法二、直接把对应列每一行的值相加(不做数据查询,在RowDataBound事件中运算)
方法三:
1. 在Web Form 的源文件中,修改GridView部分,添加 OnRowDataBound 响应函数 OnRowDataBound = "GridView1_RowDataBound"
2. 在代码页,添加该函数代码如下:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRowEventArgs ea = e as GridViewRowEventArgs;
//判断如果是底部,则执行
if (ea.Row.RowType == DataControlRowType.Footer)
{
DataRowView drv = ea.Row.DataItem as DataRowView;
// SQL 查询语句根据实际情况添加,要有合计或求平均值等函数
string strQuery = "select 'Total' as column1,'' as column2,sum(col3) as sale_col3,sum(col4)as sum_col4 from order_v" +
" where OrderNo = '" + Request.QueryString["OrderNo"] + "'";
//设置数据库连接
SqlConnection cn = new SqlConnection();
cn.ConnectionString = ConfigurationManager.ConnectionStrings["MainConnectionString"].ConnectionString;
cn.Open();
SqlCommand cmdGetItem = new SqlCommand(strQuery, cn);
SqlDataReader rdr;
rdr = cmdGetItem.ExecuteReader();
while (rdr.Read())
{
for (int i = 0; i < rdr.FieldCount; i++)
{
//填充每列的值
ea.Row.Cells[i].Text = rdr[i].ToString();
}
}
rdr.Close();
cn.Close();
}
}