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

前端 未结 9 1214
南方客
南方客 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 14:15

    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?

    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!");
        }
    }
    
    0 讨论(0)
  • 2020-12-10 14:21

    Try using SqlDataReader's GetInt32()

    rdr.GetInt32(rdr.GetOrdinal("quantity"));
    
    0 讨论(0)
  • 2020-12-10 14:22

    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"]);
    
    0 讨论(0)
提交回复
热议问题