gpt4 book ai didi

c# - 尝试 Convert.ToInt32(value) 时指定的转换无效

转载 作者:行者123 更新时间:2023-12-02 12:28:17 30 4
gpt4 key购买 nike

我正在尝试运行一个存储过程,由于某种原因它一直告诉我“指定的转换无效”。 “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

最佳答案

逻辑错误。

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

某些语言会将任何非零解释为 true,但 C# 并非如此,并且会引发异常。

您需要比较返回的值。

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

这看起来像这样:

invoiceExists = command.ExecuteScalar() != null ;

我还建议阅读这篇文章thread并考虑使用 UDF 而不是标量存储过程。

关于c# - 尝试 Convert.ToInt32(value) 时指定的转换无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13013565/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com