asp.net中為GridView添加統(tǒng)計(jì)行是常用的功能,怎么實(shí)現(xiàn)呢?下面介紹2個(gè)常見(jiàn)的方法:
前提:設(shè)置屬性ShowFooter="True"
方法一:使用SQL查詢統(tǒng)計(jì)出合計(jì)值,在綁定GridView時(shí)讓其結(jié)果賦于一個(gè)DataTable(全局變量),然后在RowDataBound事件中
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = "合計(jì)";
e.Row.Cells[3].Text = dtSum.Rows[0][0].ToString();
e.Row.Cells[4].Text = dtSum.Rows[0][1].ToString();
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 = dtSum.Rows[0][6].ToString();
e.Row.Cells[10].Text = dtSum.Rows[0][7].ToString();
e.Row.Cells[11].Text = dtSum.Rows[0][8].ToString();
}
其中dtSum是那個(gè)全局DataTable,在綁定GridView同時(shí)將SQL查詢的結(jié)果賦給它;效果如下:
方法二、直接把對(duì)應(yīng)列每一行的值相加(不做數(shù)據(jù)查詢,在RowDataBound事件中運(yùn)算)
int mysum1 = 0;
int mysum2 = 0;
protected void GridList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow )
{
DataRowView myrows=(DataRowView)e.Row.DataItem;
mysum1 +=Convert .ToInt32 (myrows[2].ToString ());
mysum2 += Convert.ToInt32(myrows[3].ToString());
}
// 合計(jì)
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = "合計(jì)";
e.Row.Cells[1].Text = mysum1.ToString();
e.Row.Cells[2].Text = mysum2.ToString();
}
}