出自ProgWiki
用途
- 例如標題列為(No, 單號, 數量, 日期)的欄位
- 在GridView的屬性設定加上 ShowFooter="True"
- 使用GridView的RowCreated事件
- 使用時須注意GridView不可分頁,不然合計會因為抓不到其它頁數的資料,而沒有意義。
程式碼範例
protected void GridViewDetail_RowCreated(object sender, GridViewRowEventArgs e)
{
switch (e.Row.RowType)
{
case DataControlRowType.Header:
break;
case DataControlRowType.Footer:
TableCellCollection tcFooter = e.Row.Cells;
tcFooter.Clear();
tcFooter.Add(new TableHeaderCell());
tcFooter[0].Attributes.Add("colspan", "2"); //合併欄位用
tcFooter[0].Attributes.Add("style", "text-align:right");
tcFooter[0].Text = "合計";
int TotalQuantity = 0; //合計數量的計算
for (int i = 0; i < GridViewDetail.Rows.Count; i++)
{
try
{
TotalQuantity += int.Parse(GridViewDetail.Rows[i].Cells[2].Text.Replace(",", ""));
}
catch
{
}
}
//合計數量
tcFooter.Add(new TableHeaderCell());
tcFooter[1].Attributes.Add("style", "text-align:right");
tcFooter[1].Text = TotalQuantity.ToString("###,###,##0");
tcFooter.Add(new TableHeaderCell());
tcFooter[2].Attributes.Add("style", "text-align:left");
tcFooter[2].Text = " ";
break;
case DataControlRowType.DataRow:
TableCellCollection tcDataRow = e.Row.Cells;
tcDataRow[0].Text = (e.Row.RowIndex + 1).ToString(); //處理No欄位用(自動編號欄位)
break;
case DataControlRowType.EmptyDataRow:
break;
}
}