只要數據庫返回結果集,我的代碼就可以正常工作。當它沒有返回它打破了,給我以下錯誤:如何防止錯誤: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 "";
}
}
哪行會引發該錯誤?檢查沒有數據返回時sumObject的值是什麼。它可能是int.Parse導致問題 –
哪一行產生錯誤? – Jason
爲什麼不使用int.'TryParse'然後傳遞值 – V4Vendetta