开发者

Getting exception while calculating the total of gridview cells

while calculating the total of gridview cells i am开发者_运维问答 getting this exception: Input string is not in correct format.

Here is my code: any help pls:

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


Your TextBox TextBox1has a non-decimal number (probably blank) in its text property in at least one row of the GridView.


Write it this way:

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


To prevent the exception, first check to make sure you have a decimal number. To do this without throwing an exception, use TryParse method:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜