asp.net GridView 在報表底部增加合計行
首先:在GridView 屬性設定中,ShowFooter 設為 true
方法一:使用SQL查詢統計出合計值,在繫結GridView時讓其結果賦於一個DataTable(全域性變數),然後在RowDataBound事件中
{
e.Row.Cells[0].Text ="合計";
e.Row.Cells[3].Text = dtSum.Rows[0][0].ToString();
e.Row.Cells[4].Text
e.Row.Cells[5].Text = dtSum.Rows[0][2].ToString();
e.Row.Cells[6].Text = dtSum.Rows[0][3].ToString();
e.Row.Cells[7].Text = dtSum.Rows[0][4].ToString();
e.Row.Cells[8].Text = dtSum.Rows[0][5].ToString();
e.Row.Cells[9].Text
e.Row.Cells[10].Text = dtSum.Rows[0][7].ToString();
e.Row.Cells[11].Text = dtSum.Rows[0][8].ToString();
}
其中dtSum是那個全域性DataTable,在繫結GridView同時將SQL查詢的結果賦給它;效果如下:
方法二、直接把對應列每一行的值相加(不做資料查詢,在RowDataBound事件中運算)
int mysum2 =0;
protected
{
if (e.Row.RowType == DataControlRowType.DataRow )
{
DataRowView myrows=(DataRowView)e.Row.DataItem;
mysum1 +=Convert .ToInt32 (myrows[2].ToString ());
mysum2 += Convert.ToInt32(myrows[3].ToString());
}
// 合計
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text ="合計";
e.Row.Cells[1].Text = mysum1.ToString();
e.Row.Cells[2].Text = mysum2.ToString();
}
}
方法三:
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();
}
}
文章引用自: