Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

calculating sum of column in gridview

Status
Not open for further replies.

zerkat

Programmer
Jul 12, 2007
103
US
I have a gridview in my web app and need to get the sum of one column. The gridview data is all bound by asp:boundfields. Not sure what the best way to do this is because I need the data in decimal format and boundfields are strings.

This is my code; this all happens in the RowDataBound:

Dim row As GridViewRow
Dim i As Integer
Dim cols As Intger = grdName.Columns.Count
Dim intTotal As Decimal = 0.0
Dim DevTotal As Integer = 0

If e.Row.RowType = DataControlRowType.DataRow Then
DevTotal += Convert.Int32(e.Row.Cells(3).Text)
intTotal = Convert.ToDecimal(DevTotal)
ElseIf e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells(0).Text = "Totals:"
e.Row.Cells(3).Text = intTotal.ToString
End If

Also tried this method but didn't iterate through the values of the cells,
 
Im guessing that you always only show the value of the last cell ?.

If I recall correctly RowDataBound will be called Each time a new row of data is bound, not once when the data is bound to the grid (if that makes sense).

As your code is summing to a variable that is local to your method, each time a row is bound,
Code:
Dim intTotal As Decimal = 0.0
Dim DevTotal As Integer = 0

is called, and so your totalisers are reset.

If you want to sum the data using this method, then you need to make your totalising variables page level variables, not method level ones.

HTH

K
 
dont' use e.Row.Cells(3).Text, at this point is just text for the user to read. use the backing data source instead to pull the actual data type and preform the calculation.

something like this should work
Code:
private int total = 0;
protected RowDataBound(object sender, GridViewRowDataBoundEventArgs e)
{
  if(e.RowIndex < 0) return;
  total += ((MyType)e.Row.DataItem).IntegerProperty;
}

protected GridViewBound(object sender, GridViewDataBoundEventArgs e)
{
  grid.Footer.Cells[3].Text = total.ToString("how you wan to display it");
}

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top