gpt4 book ai didi

c# - Specified cast is not valid 错误在 C#

转载 作者:行者123 更新时间:2023-11-29 01:56:12 26 4
gpt4 key购买 nike

我该如何解决?

MySqlConnection con = new MySqlConnection(myconnectionstring);
string validateinventory = "SELECT COUNT(*) FROM inventory_register WHERE barcode = @barcode";

MySqlCommand cmd = new MySqlCommand(validateinventory,con);

con.Open();
cmd.Parameters.AddWithValue("@barcode", textBox3.Text);
int Result = (int)cmd.ExecuteScalar();
con.Close();

if (Result > 0)
{
textBox3.Text = "";
MessageBox.Show("Invalid Barcode! Please Register Inventory or Enter Valid Barcode");
}

在以下行中抛出 InvalidCastException:

int Result = (int)cmd.ExecuteScalar();

最佳答案

尝试调试这样的代码:

object Result = cmd.ExecuteScalar();

我认为这将是一个 decimal,但这取决于 MySQL 的行为。在 C# 中,您不能简单地将 double 转换为 int如果它是装箱的。只需获取正确的类型并转换为它,然后才能转换为 int,如下所示:

int Result = (int)(decimal)cmd.ExecuteScalar();

此外,您可以通过var 关键字获取object,并使用Convert 类:

var objectResult = cmd.ExecuteScalar();
int Result = Convert.ToInt32(objectResult);

关于c# - Specified cast is not valid 错误在 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263029/

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