2
votes

I have a GridView with 100 records and the page size of the grid is 10. Also I need to sum a column from the gridview and show it in a label. I am using the below code in page load event to sum the gridview column and it works as expected.

int sum = 0;
for (int i = 0; i < gvDetails.Rows.Count; ++i)
{
   sum += Int.Parse(gvDetails.Rows[i].Cells[4].Value.ToString());
}
lblTotal.Text = sum.ToString(); 

This code sums the whole value, I mean the sum of 100 records. But I would need a sum only for the 10 records where each page will hold only 10 records and when I do paging and move to each page it has to show only the sum of that respective page.

To make simple I just need to sum the column values I see in the grid and not for all records.

How can this be achieved? Please suggest me.

2
There are a ton of similar questions asking for the same thing on SO. Have you checked any of them? - Yuck
@Yuck - Yes I checked all of 'em and haven't found anything close, so ended up posting here with anticipation. - Michael
Have you considered doing this with JQuery on document ready? The GridView renders as a HTML Table, you can loop the cells of a column and increment as you do so till you get the total, then append that to label.. - t_plusplus

2 Answers

1
votes

You can use the GridView_RowDataBound, execute for each page in the gridview.

0
votes

You can use PageIndex and PageSize to get current gridview page index and page size respectively and apply logic to get set of required rows in current page and loop over the required rows to get sum. Following is some code snippet to get the required number of rows in current page.

int pageidx = gvDetails.PageIndex;
int pagesize = gvDetails.PageSize;
int startidx = pageidx * pagesize;
int endidx = startidx + pagesize;
int sum = 0;
for (int i = startidx; i < endidx; i++)
{
    sum += Int.Parse(gvDetails.Rows[i].Cells[4].Value.ToString());
}
lblTotal.Text = sum.ToString();