Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...