Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 计算gridview单元格总数时获取异常_C# - Fatal编程技术网

C# 计算gridview单元格总数时获取异常

C# 计算gridview单元格总数时获取异常,c#,C#,在计算gridview单元格总数时,我遇到以下异常: 输入字符串的格式不正确。 这是我的代码:任何帮助请: public decimal GetTotal() { decimal total = 0; foreach (GridViewRow _row in GridView1.Rows) { TextBox txt = (TextBox)_row.FindControl("TextBox1"); total +=decimal.Parse( txt.

在计算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;
} 

您的文本框
TextBox1
的文本属性中至少有一行GridView中有一个非十进制数字(可能为空)。

请这样写:

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;
}

要防止出现异常,请首先检查以确保您有一个十进制数字。要在不引发异常的情况下执行此操作,请使用
TryParse
方法:

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

感谢您的回复…该问题已解决,但未计算总数,我正在从rowdatabound事件调用它,如下所示:if(e.Row.RowType==DataControlRowType.Footer){TextBox txtTotalPrice=(TextBox)e.Row.FindControl(“总计”);txtTotalPrice.Text=GetTotal().ToString();}