尝试Convert.ToInt32(value)时指定的强制转换无效

时间:2012-10-22 14:28:19

标签: c# sql-server tsql stored-procedures exception-handling

我正在尝试运行存储过程,由于某种原因,它一直告诉我"Specified cast is not valid"。 “hidSelectedExpenseIDs”是一个隐藏字段,其中填充了id的javascript数组。

示例:"hidSelectedExpenseIDs.Value"看起来像“123,124,125,126”。因此,为什么我有.Split(',')

这是我的代码:

public void hasExhistingExpenseInvoice()
{
    string[] Expenses = hidSelectedExpenseIDs.Value.Split(',');

    //check if there is an existing invoice. Then report back to the user so the
    //user knows if he/she has to check overwrite option.
    bool invoiceExists = false;

    foreach (var expense in Expenses)
    {
        var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
        var command = new SqlCommand("p_CaseFiles_Expenses_InvoiceExhists", connection);
        command.Parameters.Add(new SqlParameter("@ExpenseID", SqlDbType.Int));
        command.Parameters["@ExpenseID"].Value = Convert.ToInt32(expense);
        command.CommandType = CommandType.StoredProcedure;
        try
        {
            connection.Open();
            invoiceExists = (bool)command.ExecuteScalar();
            if (invoiceExists)
            {
                //previous invoice exhists
                Warning1.Visible = true;
                Warning1.Text = "There is an exhisting Invoice.";
            }
        }
        catch (SqlException sql)
        {
            lblStatus.Text = "Couldn't connect to the Database - Error";
            lblStatus.ForeColor = System.Drawing.Color.Red;
        }
        catch (Exception ex)//catches exception here
        {
            lblStatus.Text = "An error occured";
            lblStatus.ForeColor = System.Drawing.Color.Red;
        }
        finally
        {
            if (connection.State == ConnectionState.Open)
                connection.Close();
        }
    }
}

这是我的存储过程:

ALTER PROCEDURE dbo.[InvoiceExhists]
@ExpenseID int
AS
BEGIN
    SELECT InvNumber FROM dbo.Expenses from ExpID = @ExpenseID
END

3 个答案:

答案 0 :(得分:4)

逻辑错误。

您的查询返回一个数字,并且您尝试将其直接转换为布尔值,这不能在C#中完成。

有些语言会将任何非零解释为真,但对于C#则不然,它会抛出异常。

您需要比较返回的值。

在这种情况下,您应该检查是否有值,因为如果发票不存在,将返回NULL。

这看起来像这样:

invoiceExists = command.ExecuteScalar() != null ;

另外,我建议阅读此thread并考虑使用UDF而不是标量存储过程。

答案 1 :(得分:2)

更改您的存储过程。这符合您的要求

ALTER PROCEDURE [dbo].[InvoiceExhists]
@ExpenseID int
AS
BEGIN
if exists(select * Expenses where ExpID = @ExpenseID)
select 1
else
select 0
END

答案 2 :(得分:0)

该异常可能是由invoiceExists = (bool)command.ExecuteScalar();考虑其在try语句中发生的唯一转换引起的。您需要查看ExecuteScalar()的返回结果来解决您的问题。