C# windows 窗体程序中的“指定的强制转换无效”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2202703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:22:30  来源:igfitidea点击:

"Specified cast is not valid" error in C# windows forms program

c#sql-server

提问by jello

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.

我有一个“指定的演员表无效”错误。C# 中的 Windows 窗体应用程序。我正在尝试从表中检索值。该值是 smallint 或数字(我尝试了两个字段,都给我相同的错误),我尝试将其存储在 int 变量中。

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

采纳答案by jason

rdr["quantity"]is going to be a boxed something. If it is not an intthen 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

rdr["quantity"]将是一个盒装的东西。如果它不是 anint那么你不能直接将它拆箱到 an int(这是你想要做的),因为你必须首先将它拆箱到适当的类型(比如,short)。但这太麻烦了所以为了清楚起见你最好说

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

回答by Mitchel Sellers

Try one of the two options.

尝试两个选项之一。

int number = rdr.getInt32(rdr.GetOrdinal("quantity"));

or

或者

int number = int.parse(rdr["quantity"].ToString());

回答by Mitchel Sellers

  if(rdr["quantity"].GetType() != typeof(int))
    throw new InvalidOperationException(
      "quantity is a " + rdr["quantity"].GetType());
  int number = (int)rdr["quantity"]; // error is here

回答by David

Have you tried

你有没有尝试过

int number=convert.toint16(rdr["quantity"]); 

回答by John Saunders

I bet quantityis NULL, which is not an integer.

我的赌注quantityNULL,这是不是一个整数。

回答by statenjason

Try using SqlDataReader's GetInt32()

尝试使用 SqlDataReader 的 GetInt32()

rdr.GetInt32(rdr.GetOrdinal("quantity"));

回答by marc_s

Silly suggestion, maybe - but have you considered trying this - grab the result from your SqlDataReaderas an instance of objectand then checking what type it is? No one can tell you better what it reallyis than the CLR type system! :-)

愚蠢的建议,也许 - 但你有没有考虑过尝试这个 - 从你SqlDataReader的实例中获取结果object,然后检查它是什么类型?没有人能更好地告诉你它真的比CLR类型系统!:-)

using (SqlDataReader rdr = cmd.ExecuteReader()) 
{
    while (rdr.Read())
    {
        object obj = rdr["quantity"];

        if(obj != null)
        {
            string objType = obj.GetType().FullName;
        }
    }
 }

If you do get a value back, you can check what type it is and hopefully convert it accordingly, depending on your results.

如果您确实得到了一个值,您可以检查它是什么类型,并希望根据您的结果进行相应的转换。

回答by Billy Coover

Since you said that you know what the value should be because you created the database... Can you check that rdr["quantity"] has a value then run a try parse on it?

既然你说你知道值应该是什么,因为你创建了数据库......你能检查 rdr["quantity"] 有一个值然后运行一个 try parse 吗?

if(rdr["quantity"] != null) {
    int? number = null;
    if(int.TryParse(rdr["quantity"].ToString(), out number)) {
        Console.WriteLine("Hurray, I have an int. Up vote Coov!");
    }
}

回答by Roki

 sl_id = Convert.ToInt32(lblintroducerid.Text.ToString());
 sl_rank = Convert.ToInt32(lblassorank.Text.ToString());