2011-07-28 37 views
2

我正在處理我的第一個asp.net項目,並且似乎無法通過此錯誤。下一步是計算兩個值之間的差異(每個都在單獨的gridview中)並在文本框中顯示差異。爲了調試我有一個文本框來顯示每個值,所以現在有3個文本框。其中一個值是可編輯的GridView,當我點擊編輯我得到以下異常:發生在GridView編輯上,「輸入字符串的格式不正確」

System.FormatException消息=輸入字符串的不以 正確的格式。源= mscorlib程序堆棧跟蹤: 在System.Number.StringToNumber(字符串str,的NumberStyles 選項,NumberBuffer &數,的NumberFormatInfo信息,布爾 parseDecimal) 在System.Number.ParseDecimal(字符串值,的NumberStyles 選項的NumberFormatInfo numfmt) 在System.Decimal.Parse(字符串或多個) 在 caremaster.caremaster.FieldDetailsGridView_RowDataBound(對象發件人, GridViewRowEventArgs E)在M:\我的文檔\ file.cs:線48
的InnerException:

下面是一個代碼示例:

protected void TotalNGridView_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     string totNUnits = e.Row.Cells[0].Text; 
     unitsN.Text = totNUnits; 
     applied = decimal.Parse(e.Row.Cells[0].Text.ToString())      
    } 
} 

protected void FieldDetailsGridView_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     string recNUnits = e.Row.Cells[4].Text; 
     recomN.Text = recNUnits; 
     recommend = decimal.Parse(e.Row.Cells[4].Text.ToString()); // exception thrown 
     calcNtoApply(); 
    }   
} 

protected void calcNtoApply() 
{ 
    decimal final; 
    final = recommend - applied;   
    finalN.Text = final.ToString(); 
} 

現在我檢索上GridView_RowDataBound數據。我認爲我對GridView事件的不同之處感到困惑。由於單擊「編輯」時發生此錯誤,我應該檢索RowDataEditing中推薦的值嗎?

這裏有一些額外的細節:

decimal recommend; 

decimal applied; 

預先感謝任何批評和指導。

+0

當你調試時,e.Row.Cells [4] .Text'的值是什麼?順便說一句,你不需要在'e.Row.Cells [4] .Text.ToString()'處使用'.ToString()'',因爲'.Text'已經是字符串類型。 –

+1

值爲250,對於測試,我編輯並將其更改爲251.感謝ToString()的正面評價,我嘗試了一堆瘋狂的東西試圖讓它工作。 – rdizzler

回答

2

使用Decimal.TryParse方法。

​​
+0

這擺脫了例外,謝謝! – rdizzler

+0

@rdizzler,我也投了贊成票。但是,由於它是一個'TryParse',所以你一直沒有'推薦'的值。你只是壓制這個異常。你現在是否按照你應該得到的輸出? –

+0

輸出按預期工作。感謝您將這引起我的注意。 – rdizzler

0

錯誤很明顯:decimal.Parse無法轉換e.Row.Cells[4]中的任何值。那裏有什麼價值?

嘗試做這樣的:

if (e.Row.RowType == DataControlRowType.DataRow) 
{ 
    string recNUnits = e.Row.Cells[4].Text; 

    recomN.Text = recNUnits; 

    if(!String.IsNullOrEmpty(e.Row.Cells[4].Text)) 
    { 
     recommend = decimal.Parse(e.Row.Cells[4].Text); 
    } 

    calcNtoApply(); 
} 
+0

謝謝@Leniel Macaferi – rdizzler