Michael
Michael

Reputation: 305

Sum Gridview column with paging

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.

Upvotes: 2

Views: 1662

Answers (2)

Fremin Abreu
Fremin Abreu

Reputation: 127

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

Upvotes: 1

Arindam Nayak
Arindam Nayak

Reputation: 7462

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(); 

Upvotes: 0

Related Questions