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”>


<asp:BoundColumn DataField=”Product” HeaderText=”Product”/>

<asp:BoundColumn DataField=”Price” HeaderText=”Price” DataFormatString=”{0:C}”/>

<asp:EditCommandColumn EditText=”Edit” UpdateText=”Update” CancelText=”Cancel” />


And the code:
        private void Page_Load(object sender, System.EventArgs e)


//creating mock table for data

DataTable dt = new DataTable();



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;


//adding totals row

DataGridItem row = new DataGridItem(-1, -1, ListItemType.Separator);

TableCell cell = new TableCell();


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”);


cell = new TableCell();



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.