0
votes

I have a DataTable that I bind to a gridview on a website. The table has columns of data for several months. I want the user to be able to update the gridview in various ways, for example summing every 12 months (columns) of data. I have accomplished this before by having a foreach loop go through and sum these columns of each row and add it to a table with different columns,

foreach (DataRow dr in data.Rows)
{
    newRow[6] = Convert.ToDouble(dr[6]) + Convert.ToDouble(dr[7]) + Convert.ToDouble(dr[8]);

    et cetera 

    newDataTable.Rows.Add(newRow);
}

but I find this takes a while to run.

Is there a more efficient method? Since I have the table with month by month data stored in a session variable. Can I easily pass this to a method that will condense it without having to create a new data table and rebuild it row by row? I'm thinking something along the lines of using DataTable.Select but instead of returning a DataRow[] I would need a DataColumn[] to sum across? I'm not entirely sure.

Maybe there isn't another way, but I was wondering if anyone had any approaches that would be better. Thank you,

1

1 Answers

0
votes

The usage of session variable to contain a large data is not a good approach since this value is stored as hidden variable which may costs high in term of resources. For further details see this link Assigning DataTable to ViewState is a good way?

and for sum 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();