GridView的Footer列加入合計的計算

出自ProgWiki

跳轉到: 導航, 搜尋

用途

  1. 在GridView的屬性設定加上 ShowFooter="True"
  2. 使用GridView的RowCreated事件
  3. 使用時須注意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;
		}
	}
個人工具
名字空間
變換
動作
導航
分類
其他
技術類News或部落格
工具箱