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

前端 未结 9 1221
南方客
南方客 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: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.

提交回复
热议问题