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.