2012-05-03 26 views
0

只要數據庫返回結果集,我的代碼就可以正常工作。當它沒有返回它打破了,給我以下錯誤:如何防止錯誤:System.FormatException:輸入字符串的格式不正確

System.FormatException: Input string was not in a correct format. 

這裏是我的代碼:

DataTable data = GeneralFunctions.GetData(query); 
object sumObject; 
sumObject = data.Compute("Sum(Minutes_Spent)", ""); 
if (reportType == 1) 
{ 
    RepeaterPCBillable.DataSource = data; 
    RepeaterPCBillable.DataBind(); 
    LabelPCBillable.Text = ParseTime(int.Parse(sumObject.ToString())) == null 
     ? ParseTime(int.Parse(sumObject.ToString())) 
     : ""; // ERROR HERE 
} 
else 
{ 
    RepeaterDTSTBillable.DataSource = data; 
    RepeaterDTSTBillable.DataBind(); 
    LabelDTSTBillable.Text = ParseTime(int.Parse(sumObject.ToString())) == null 
     ? ParseTime(int.Parse(sumObject.ToString())) 
     : ""; 
} 

分析時:

protected string ParseTime (int TotalMinutes) 
{ 
    int hours = TotalMinutes/60; 
    int minutes = TotalMinutes % 60; 

    if (hours == 0) 
    { 
     return String.Format("{0} minutes", minutes); 
    } 
    else if (hours == 1) 
    { 
     return String.Format("{0} hour and {1} minutes", hours, minutes); 
    } 
    else if (hours > 1) 
    { 
     return String.Format("{0} hours and {1} minutes", hours, minutes); 
    } 
    else 
    { 
     return ""; 
    } 
} 
+0

哪行會引發該錯誤?檢查沒有數據返回時sumObject的值是什麼。它可能是int.Parse導致問題 –

+0

哪一行產生錯誤? – Jason

+1

爲什麼不使用int.'TryParse'然後傳遞值 – V4Vendetta

回答

1

爲什麼不只是添加下面的檢查:

if (data.Rows.Count > 0) 
{ 
    // do your stuff 
} 
+0

這很好,謝謝。 :) –

+0

@James Wilson - 不客氣:) – dcp

+2

@JamesWilson:現在你可以接受答案! :D –

1
using (DataTable data = GeneralFunctions.GetData(query)) 
{ 
    if (data != null && data.Rows.Count > 0) 
    { 
     object sumObject; 
     sumObject = data.Compute("Sum(Minutes_Spent)", ""); 
     if (reportType == 1) 
     { 
      RepeaterPCBillable.DataSource = data; 
      RepeaterPCBillable.DataBind(); 
      LabelPCBillable.Text = ParseTime(int.Parse(sumObject.ToString())) == null 
       ? ParseTime(int.Parse(sumObject.ToString())) 
       : ""; 
     } 
     else 
     { 
      RepeaterDTSTBillable.DataSource = data; 
      RepeaterDTSTBillable.DataBind(); 
      LabelDTSTBillable.Text = ParseTime(int.Parse(sumObject.ToString())) == null 
       ? ParseTime(int.Parse(sumObject.ToString())) 
       : ""; 
     } 
    } 
} 
0

在哪裏發生異常?這段代碼的哪一行?

我瘋狂的猜測是,沒有結果,Compute()函數爲它的第一個Minutes_Spent值得到一個空字符串的輸入,它不能解析成一個整數。

在運行Compute()之前,解決方案可能會對至少有一行的結果集執行檢查。如果有零行,請提供一些默認值,例如零或「(無結果)」以顯示。

+0

我更新了OP上的錯誤行。 –

相關問題