如何在datagridview的末尾对列进行求和

时间:2016-12-30 07:49:12

标签: c#

我想在我的DataGridView末尾汇总列,如下所示:

enter image description here

      column1 | column2  |column3|  column3   |
      --------+----------+-------+------------|
      1       | 2        |    3  |     4      |
     ---------+----------+-------+------------|
      2       |  4       |     7 |      9     |
--------------+----------+-------+------------|
total 3        6           10         13
-----------------------------------------------

2 个答案:

答案 0 :(得分:1)

您可以在网格视图的页脚中添加总计:

 decimal total = dt.AsEnumerable().Sum(row => row.Field<decimal>("Amount"));
                    GridView1.FooterRow.Cells[1].Text = "Total";
                    GridView1.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
                    GridView1.FooterRow.Cells[2].Text = total.ToString("N2");

答案 1 :(得分:0)

您可以使用DataBound事件,在所有行都是数据绑定后触发,Amount总和我添加到标签。标签可以在页脚中添加Total

protected void GridDataBound(object sender, EventArgs e)
{
    GridView gridView = (GridView)sender;
    DataTable dt= (DataTable)gridView .DataSource;
    decimal sum= dt.AsEnumerable().Sum(r => r.Field<decimal>("Amount"));
    totalLabel.Text = sum.ToString();
}

或将sum添加为最后一行

protected void GridDataBound(object sender, EventArgs e)
{
 GridView gridView = (GridView)sender;
 DataTable dt = (DataTable)gridView.DataSource;
 decimal sum =  dt.AsEnumerable().Sum(r => r.Field<decimal>("Amount"));
 var newRow = dt.NewRow();
 newRow["Name"] = "Total";
 newRow["Amount"] = sum.ToString();
 dt.Rows.Add(newRow);
}