问题描述
在计算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;
}
解决方法
您的TextBox
TextBox1
在GridView的至少一行中的text属性中具有一个非十进制数字(可能为空白)。
,这样写:
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);
}