C# 计算gridview单元格总数时获取异常
在计算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.
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();}