2011-05-23 30 views
0

在计算gridview单元格总数时,我得到以下例外: 输入字符串格式不正确。计算GridView单元格总数时出现异常

这里是我的代码:任何帮助请:

public decimal GetTotal() 
{ 
    decimal total = 0; 
    foreach (GridViewRow _row in GridView1.Rows) 
    { 
    TextBox txt = (TextBox)_row.FindControl("TextBox1"); 
    total +=decimal.Parse(txt.Text); 
    } 
    return total; 
} 

回答

1

你的文本框TextBox1具有非十进制数(可能是空白)在其文本属性在GridView中的至少一个排。

0

写这样说:

public decimal GetTotal() 
{ 
    decimal total = 0; 

    foreach (GridViewRow _row in GridView1.Rows) 
    { 
     TextBox txt = (TextBox)_row.FindControl("TextBox1"); 
     decimal decimalValue; 
     if (decimal.TryParse(txt.Text, out decimalValue)) 
     { 
      total += decimal.Parse(txt.Text); 
     } 
    } 

    return total; 
} 
+0

感谢您的回复......这个问题解决了,但总不能计算,我打电话是::要做到这一点,没有抛出异常,使用TryParse方法 如果( e.RowType == DataControlRowType.Footer) {TextBox txtTotalPrice =(TextBox)e.Row.FindControl(“total”); txtTotalPrice.Text = GetTotal()。ToString(); } – jims 2011-05-23 06:30:36

0

要防止异常,首先检查,以确保你有一个十进制数。从 RowDataBound事件像下面

foreach (GridViewRow _row in GridView1.Rows) 
{ 
TextBox txt = (TextBox)_row.FindControl("TextBox1"); 
decimal value; 
if (decimal.TryParse(txt.Text, out value) 
    total +=decimal.Parse(txt.Text); 
}