Reputation: 99
I want to sum column at the end of my DataGridView
as shown here:
column1 | column2 |column3| column3 |
--------+----------+-------+------------|
1 | 2 | 3 | 4 |
---------+----------+-------+------------|
2 | 4 | 7 | 9 |
--------------+----------+-------+------------|
total 3 6 10 13
-----------------------------------------------
Upvotes: 2
Views: 4446
Reputation: 6203
You can use DataBound
event, it's firing after all rows were databound, Amount
sum i added to label. Label can be added in footer as 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();
}
or add sum as last row
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);
}
Upvotes: 1
Reputation: 1635
You can add the Total in footer of gridview :
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");
Upvotes: 1