0

I am using RowDataBound Event to calculate the sum of a column data. The variable in which i am getting the sum of column values is becoming zero at the end of the rowdatabound event, because its initial value is zero. How can I store the sum of values in a variable to use its value outside the event. Thanks

int totSubTot = 0;
public double TotalAmount;
protected void gvShowOrder_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        totSubTot += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SubTotal"));        
    }
    else if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[2].Text = "Grand Total";
        e.Row.Cells[2].Font.Bold = true;

        e.Row.Cells[3].Text = totSubTot.ToString();
        e.Row.Cells[3].Font.Bold = true;
        TotalAmount = Convert.ToDouble(e.Row.Cells[3].Text);
    }
}
RePierre
  • 9,358
  • 2
  • 20
  • 37
Saqib Zaman
  • 3
  • 1
  • 1
  • 3

3 Answers3

3

Why not get the sum from data source?

var gridView = sender as GridView;
var dataSource = gridView.DataSource as IEnumerable<YourDataObject>;
e.Row.Cells[3].Text = dataSource.Sum(item => item.YourProperty).ToString();
RePierre
  • 9,358
  • 2
  • 20
  • 37
0

Your logic seems to be off.

In your first if-statement you assign totSubTot to the DataItem, but in your else you are not assigning anything to it.

It probably only goes into one of your if/else if and thats why. Try this

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            totSubTot += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SubTotal"));
            TotalAmount =Convert.ToDouble(totSubTot);
        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {
            totSubTot += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SubTotal"));
            TotalAmount =Convert.ToDouble(totSubTot);

            e.Row.Cells[2].Text = "Grand Total";
            e.Row.Cells[2].Font.Bold = true;

            e.Row.Cells[3].Text = totSubTot.ToString();
            e.Row.Cells[3].Font.Bold = true;
        }
user1021726
  • 638
  • 10
  • 23
0

please try this

static int totSubTot = 0; 
static double TotalAmount; 
protected void gvShowOrder_RowDataBound(object sender, GridViewRowEventArgs e) {
    if (e.Row.RowType == DataControlRowType.DataRow) {
        totSubTot += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SubTotal"));        
    } else if (e.Row.RowType == DataControlRowType.Footer) {
        e.Row.Cells[2].Text = "Grand Total";
        e.Row.Cells[2].Font.Bold = true;

        e.Row.Cells[3].Text = totSubTot.ToString();
        e.Row.Cells[3].Font.Bold = true;
        TotalAmount = Convert.ToDouble(e.Row.Cells[3].Text);
    }
}
andrewsi
  • 10,807
  • 132
  • 35
  • 51