How to: Add a totals row to your DataGrid before the footer/pager – level 300
In my own dealings, I’ve had to take control of how a DataGrid was rendered. One particular example is adding a Totals row to a grid BEFORE the footer. Here’s a sample:
<asp:DataGrid ID=”dgd” Runat=”server” AutoGenerateColumns=”False”>
<Columns>
<asp:BoundColumn DataField=”Product” HeaderText=”Product”/>
<asp:BoundColumn DataField=”Price” HeaderText=”Price” DataFormatString=”{0:C}”/>
<asp:EditCommandColumn EditText=”Edit” UpdateText=”Update” CancelText=”Cancel” />
</Columns>
</asp:DataGrid>
And the code:private void Page_Load(object sender, System.EventArgs e)
{
//creating mock table for data
DataTable dt = new DataTable();
dt.Columns.Add(“Product”);
dt.Columns.Add(“Price”);
dt.Rows.Add(new object[]{“Shoes”, “12.90”});
dt.Rows.Add(new object[]{“Socks”, “3.50”});
dt.Rows.Add(new object[]{“Underpants”, “8.40”});
//binding mock data
dgd.DataSource = dt;
dgd.DataBind();
//adding totals row
DataGridItem row = new DataGridItem(-1, -1, ListItemType.Separator);
TableCell cell = new TableCell();
row.Cells.Add(cell);
cell = new TableCell();
//calculate total
decimal total = 0;
foreach(DataGridItem dgi in dgd.Items)
{
total += decimal.Parse(dgi.Cells[1].Text);
}
cell.Font.Bold = true;
cell.Text = total.ToString(“c”);
row.Cells.Add(cell);
cell = new TableCell();
row.Cells.Add(cell);
dgd.Controls[0].Controls.Add(row);
}
I merely create a new DataGridItem, add what I want, and add it to my grid. I’ve used this concept several times, and I hope it helps out someone else.
This would be a nice way to do it:
Creating Expression Columns
workTable.Columns.Add("SalesTax", typeof(Double), "Total * 0.086");
If you needed an extra column, then yes, but my example demonstrates how to add an extra row to a DataGrid.
Good Method.
Off the top of my head another way to do it would be to capture ItemDataBind on each row and do the calculation.
Then add the row at the end, after databinding.
Hi,
This method does not seem to work if the datagrid contains any hidden columns, in that case the manually added row renders as a empty table row (<tr></tr>)… any experience?
Hi
You have to use the ItemDataBind this allows you to access the Grid onload
Excellent post, very useful and worked without any tweaking.