Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 指定的强制转换在C中无效错误#_C#_Mysql_Winforms_Casting - Fatal编程技术网

C# 指定的强制转换在C中无效错误#

C# 指定的强制转换在C中无效错误#,c#,mysql,winforms,casting,C#,Mysql,Winforms,Casting,我如何解决这个问题 MySqlConnection con = new MySqlConnection(myconnectionstring); string validateinventory = "SELECT COUNT(*) FROM inventory_register WHERE barcode = @barcode"; MySqlCommand cmd = new MySqlCommand(validateinventory,con); con.Open(); cmd.Para

我如何解决这个问题

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();
我认为这将是一个
十进制
,但这取决于MySQL的行为。在C语言中,你不能简单地将一个
double
转换成
int
,如果它被装箱的话。只需获取正确的类型并转换为它,然后才能转换为
int
,如下所示:

int Result = (int)(decimal)cmd.ExecuteScalar();
此外,您还可以通过
var
关键字获取
对象
,并使用
Convert
类:

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

也许你应该说明你得到的错误,以及在哪一行。嗨,我在“int result=(int)cmd.executescalar();@Ameena你确定
executescalar()的结果吗
是一个整数值吗?调试器怎么说?ExecuteScalar实际返回值的可能重复?在C#中,您完全可以显式地将一个double转换为整数。为什么
COUNT
返回一个double?@Frank
decimal
或double将在选中的上下文中引发异常,因为
double
值已装箱,需要先转换为它的实型。这是重复的:@Frank更新了答案。@VMAtm谢谢。现在问题是if条件,我应该如何检查结果的值是否为null或null(>0或=0)