指定的转换使用C#有效的错误 [英] Specified cast is not valid error using C#

查看:119
本文介绍了指定的转换使用C#有效的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想储存在C#中的变量的SELECT语句的结果,但得到这个错误


  

规定的强制转换无效


当我运行它。我不知道如何解决它,请帮助

  SqlConnection的CON1 =新的SqlConnection(ConfigurationManager.ConnectionStrings [MyConnectionString]的ConnectionString);        CMD1的SqlCommand =新的SqlCommand(SELECT CAST(圆(SUM(CAST(AvgNumbers为数字(12,2))),2)十进制(12,2))AS [平均天数]从MainTable,CON1);        cmd1.Connection = CON1;
        con1.Open();
        INT32结果=(Int32)已cmd1.ExecuteScalar();
        con1.Close();


解决方案

cmd1.ExecuteScalar()没有返回一个整数盒装。其分配给一个对象,看看它在调试器,看看它到底是什么。

我猜这将是返回一个小数或双,而你需要做的:

 的Int32结果=(Int32)已(双)cmd1.ExecuteScalar();

或者

 的Int32结果=(Int32)已(十进制)cmd1.ExecuteScalar();

要保持十进制值,只是这样做:

 十进制结果=(十进制)cmd1.ExecuteScalar();

如果你需要,你可以十进制转换为双:

 双重结果=(双)(十进制)cmd1.ExectuteScalar();

I am trying to store a select statement result in C# variable but getting this error

"Specified cast is not valid"

when i run it. I am not sure how to resolve it please help

SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

        SqlCommand cmd1 = new SqlCommand("select cast(round(sum(CAST(AvgNumbers AS numeric(12,2))),2) as decimal(12,2)) AS [Average Days] from MainTable ", con1);

        cmd1.Connection = con1;
        con1.Open();
        Int32 result = (Int32)cmd1.ExecuteScalar();
        con1.Close();

解决方案

cmd1.ExecuteScalar() is not returning a boxed integer. Assign it to an object and look at it in the debugger to see what it really is.

I'm guessing it's going to be returning a Decimal or a double, and you need to do:

Int32 result = (Int32)(double)cmd1.ExecuteScalar();

Or:

Int32 result = (Int32)(Decimal)cmd1.ExecuteScalar();

[EDIT in response to a question in commments below]

To keep the decimal value, just do this:

Decimal result = (Decimal) cmd1.ExecuteScalar();

If you needed to, you could cast the decimal to a double:

double result = (double)(Decimal) cmd1.ExectuteScalar();

这篇关于指定的转换使用C#有效的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆