Tuesday, 29 July 2014

How to calculate sum of columns total in gridview footer in ASP.NET

In this, I am going to explain how to display the sum of total of columns in gridview footer. I have a gridview with multiple rows and columns and wanna display sum of total of columns in gridview footer, that's why using DataBound.
protected void gridview1_DataBound(object sender, EventArgs e)
    {
        {
            int TotalRows = gridview1.Rows.Count; // to count total rows
            if (TotalRows > 0) // check if any rows exist
            {
                // to count total no. of column exist
                int TotalCol = gridview1.Rows[0].Cells.Count;

                gridview1.FooterRow.Cells[2].Text = "<b>" + "Total : " + "</b>";
                gridview1.FooterRow.Cells[2].ForeColor = System.Drawing.Color.Green;
                
                // 'i=3' means sum-up start from fourth column
                for (int i = 3; i < TotalCol; i++)
                {
                    // to skip any specific column sum
                    if (gridview1.HeaderRow.Cells[i].Text == "Remarks")
                    {
                        continue; // loop continues to execute with the next iteration
                    }
                    double sum = 0.0;

                    for (int j = 0; j < TotalRows; j++)
                    {
                        sum += gridview1.Rows[j].Cells[i].Text != "&nbsp;" ? double.Parse(gridview1.Rows[j].Cells[i].Text) : 0.00;
                    }
                    
                    // bind it to on the basis of their respective column(s)
                    gridview1.FooterRow.Cells[i].Text = "<b>" + sum.ToString() + "</b>";
                }
            }
        }
    }
That’s it!!…..Happy Programming...

No comments:

Post a Comment