0

只要数据库返回结果集,我的代码就可以正常工作。当它什么都不返回时,它会中断并给我以下错误:

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 "";
    }
}
4

3 回答 3

1

为什么不添加以下检查:

if (data.Rows.Count > 0)
{
   // do your stuff
}
于 2012-05-03T16:20:04.797 回答
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()))
                : "";
        }
    }
}
于 2012-05-03T16:22:02.253 回答
0

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

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

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

于 2012-05-03T16:22:16.017 回答