"指定的转换是无效的"在C#中的Windows错误形式的程序 [英] "Specified cast is not valid" error in C# windows forms program

查看:438
本文介绍了"指定的转换是无效的"在C#中的Windows错误形式的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指定的转换无效错误。在C#Windows窗体应用程序。我试图从表中检索的值。该值可以是一个smallint或数字(我想这两个领域,既给我同样的错误),我尝试将它保存在一个int变量。

这里的源:

 使用(RDR SqlDataReader的= cmd.ExecuteReader())//select * from表,其中字段名=+值
{ 而(rdr.Read())
 {
  INT数=(INT)RDR [数量]; //错误是在这里


解决方案

RDR [数量] 将是一个盒装的东西。如果它不是一个 INT 则不能直接拆箱它的 INT (这是您要做),你必须首先它拆箱为适当的类型(例如,)。但是,这是太麻烦所以为了清楚起见,你就要去说好

  Convert.ToInt32(RDR [数量]);

I'm having a "Specified cast is not valid" error. Windows form application in C#. I'm trying to retrieve a value from a table. The value is either a smallint, or a numeric(i tried both fields, both give me the same error), and I try to store it in an int variable.

here's the source:

using (SqlDataReader rdr = cmd.ExecuteReader()) //"select * from table where fieldname = " + value
{

 while (rdr.Read())
 {
  int number = (int)rdr["quantity"]; // error is here

解决方案

rdr["quantity"] is going to be a boxed something. If it is not an int then you can not unbox it directly to an int (which is what you are trying to do) as you have to first unbox it to the appropriate type (say, short). But this is too cumbersome so for clarity you're better off saying

Convert.ToInt32(rdr["quantity"]);

这篇关于"指定的转换是无效的"在C#中的Windows错误形式的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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