Q:

Calculating Total in Gridview when autogenerate columns is set to false

I have a gridview that has autogeneratecolumns set to false. The columns can be generated dynamically depending on the data so this gridview is showing how many hours a person spend on each application - Test1, test2, Test3 and Test4 are the name of the person and Projects (applications) are listed on the left. Below is the Gridview
   Projects       Test1        Test2       Test3

    Tickets           8           10    0

    maintenance       9       11         13

     Writing web       8            9          8

    Total             25          30           21    

The above grid view can change dynamically when I add a new project in the database and a new person enters his hours for the new project so the above grid view can become like this
Projects       Test1        Test2       Test3      Test4

Tickets           8           10    0          0

maintenance       9       11         13        0

Writing web       8            9          8        0

VSS                                                 12.5

Total             25          30           21      12.5

I need to calculate the total in the footer of the gridview dynamically for all the columns . How can I achieve this when I don't know how many columns can there be and the columns are coming from the query. I am just displaying the grid view from my query and that's why I set the autogeneratecolumns to false.
any help will be appreciated.

A:

You can do that in the OnRowDataBound event of the GridView.
decimal total;

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the current row is a datarow or the footer row
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //cast the row back to a datarowview
        DataRowView row = e.Row.DataItem as DataRowView;

        //add the column value to the totals
        total += Convert.ToDecimal(row["Test1"]);

        //or by column index
        total += Convert.ToDecimal(row[0]);
    }
    else if (e.Row.RowType == DataControlRowType.Footer)
    {
        //find a label in the footer with findcontrol
        Label label = e.Row.FindControl("Label1") as Label;

        //set the total value in the label
        label.Text = string.Format("{0:N2}", total);

        //set the footer value by cell index instead of a label
        e.Row.Cells[1].Text = string.Format("{0:N2}", total);
    }
}

