如何防止错误:System.FormatException:输入字符串的格式不正确

时间:2012-05-03 16:17:14

标签: 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 ( 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 "";
    }
}

3 个答案:

答案 0 :(得分:1)

为什么不添加以下支票:

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

答案 1 :(得分: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()))
                : "";
        }
    }
}

答案 2 :(得分:0)

异常究竟发生在哪里?在这段代码的哪一行?

我的猜测是,没有结果,Compute()函数获取一个空字符串的输入,其第一个值为Minutes_Spent,它无法解析为整数。

解决方案可能是在运行Compute()之前检查至少有一行的结果集。如果零行,则提供一些默认值,例如零或“(无结果)”以显示。

相关问题