C# 如何防止错误:System.FormatException:输入字符串的格式不正确
只要数据库返回结果集,我的代码就可以正常工作。当它不返回任何内容时,它会中断并给出以下错误:C# 如何防止错误:System.FormatException:输入字符串的格式不正确,c#,asp.net,C#,Asp.net,只要数据库返回结果集,我的代码就可以正常工作。当它不返回任何内容时,它会中断并给出以下错误: System.FormatException: Input string was not in a correct format. 这是我的密码: DataTable data = GeneralFunctions.GetData( query ); object sumObject; sumObject = data.Compute( "Sum(Minutes_Spent)", "" ); if (
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 "";
}
}
为什么不添加以下检查:
if (data.Rows.Count > 0)
{
// do your stuff
}
异常具体发生在哪里?在代码的哪一行 我的猜测是,如果没有结果,Compute()函数的第一个值Minutes_将得到一个空字符串的输入,它无法将其解析为整数
解决方案可能是在运行Compute()之前,对至少有一行的结果集执行检查。如果有零行,则提供一些默认值,如零或“(无结果)”以显示。哪行抛出该错误?当没有返回数据时,检查sumObject的值是多少。可能是int.Parse引起了问题。哪一行产生了错误?为什么不使用int.
TryParse
然后传递值?我用引发错误的行更新了OP。@huMptyduMpty抱歉,是在后台编码中。。)
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()))
: "";
}
}
}