2011-05-23 25 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); 
}