首先設定 showfooter=true;
在首頁定義兩個變數: public float Mysum1; public float Mysum2;
然後寫 RowDatabind方法:
protected void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
base.GridView_RowDataBound(e, 1, 18);
base.GridView_RowDataBound(e, 9, 28);
DataKey Keys = GridView1.DataKeys[e.Row.RowIndex];
TableCell myTableCell;
myTableCell = e.Row.Cells[5];
HyperLink LB = (HyperLink)(myTableCell.Controls[0]);
LB.Enabled = Keys["SZLX"].ToString().Trim() == "0";
DataRowView MyRows=(DataRowView)e.Row.DataItem;
Mysum1 += MyRows["SR"] is DBNull ? 0 : float.Parse(MyRows["SR"].ToString());
Mysum2 += MyRows["ZC"] is DBNull ? 0 : float.Parse(MyRows["ZC"].ToString());
/* 注意這裡MyRows["SR"]網上的例子用的是索引號MyRows[6],這是假定你所顯示的欄位順序和資料來源的順序是一至的,事實上我們都 是用select* from 這樣的語句,所以用序號會出現錯誤,所以這個地方應該用欄位用而不是索引號 ,出現資料類型轉換錯誤我覺得可能就是這個原因造成的*/
}
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = "合計:";
e.Row.Cells[6].Text = string.Format("{0:f2}", Mysum1);
e.Row.Cells[7].Text = string.Format("{0:f2}", Mysum2);
}
}