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

前端 未结 9 1213
南方客
南方客 2020-12-10 13:20

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 numer

相关标签:
9条回答
  • 2020-12-10 13:55
      if(rdr["quantity"].GetType() != typeof(int))
        throw new InvalidOperationException(
          "quantity is a " + rdr["quantity"].GetType());
      int number = (int)rdr["quantity"]; // error is here
    
    0 讨论(0)
  • 2020-12-10 14:01

    Have you tried

    int number=convert.toint16(rdr["quantity"]); 
    
    0 讨论(0)
  • 2020-12-10 14:03

    I bet quantity is NULL, which is not an integer.

    0 讨论(0)
  • 2020-12-10 14:08

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

    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.

    0 讨论(0)
  • 2020-12-10 14:09
     sl_id = Convert.ToInt32(lblintroducerid.Text.ToString());
     sl_rank = Convert.ToInt32(lblassorank.Text.ToString());
    
    0 讨论(0)
  • 2020-12-10 14:14

    Try one of the two options.

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

    or

    int number = int.parse(rdr["quantity"].ToString());
    
    0 讨论(0)
提交回复
热议问题