I am trying to find the sum of all the cells of a column in my gridview. However I am getting the error:
I am trying to calculate the entire column and throw it in a label outside of the gridview.
The output from Row.Cells[4] is 459.00
Input string was not in a correct format.
on line: Line 509: sum += Decimal.Parse(c.Text);
Here is my code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
// Set the capacity label text
Label4.Text = e.Row.Cells[4].Text;
// Calc the sum of all of the row values
decimal sum = 0;
foreach (TableCell c in e.Row.Cells)
{
sum += Decimal.Parse(c.Text);
}
// Set the sum label text value
Label5.Text = sum.ToString();
}
}
Make the sum a global variable.
decimal sum = 0;
then for each row add to the global variable:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItem != null)
{
// Set the capacity label text
sum += Decimal.Parse(e.Row.Cells[4].Text);
}
}
then in the page_prerender put the following:
// Set the sum label text value
Label5.Text = sum.ToString();
You also may want to check that Row.ItemType is an item, not the header. Also, it's safer to do:
decimal val;
foreach (..)
{
//only call Trim() if you know the text is not null.
If (Not Decimal.TryParse(c.Text.Trim()), out val) {
//error condition; you can throw an exception just for testing to verify something is or isn't right
throw new Exception("Error, field is not a decimal: " + c.Text);
}
else {
sum += val;
}
Also, any totalling has to be done outside of the ItemDataBound event too. So Setting the total to a label isn't the right time for that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.