Saturday, November 12, 2005

Displaying total of a column in the datagrid footer.

There are many occassions when you need to find the total of a particular column in a datagrid and display it in the footer as shown in the figure.

An easy way to do so is to implement the adding function in the ItemDataBound event of the datagrid. The ItemDataGrid event is called every time a item is bound. A Sample code is given below.

private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType==ListItemType.AlternatingItem e.Item.ItemType==ListItemType.Item)
{
total+= double.Parse(e.Item.Cells[1].Text);
}
if(e.Item.ItemType==ListItemType.Footer)
{
e.Item.Cells[0].Text="Total";
e.Item.Cells[1].Text=total.ToString();
}
}