更新时间:2023-02-17 12:37:31
RDR [数量]
将是一个盒装的东西。如果它不是一个 INT
则不能直接拆箱它的 INT
(这是您要做),你必须首先它拆箱为适当的类型(例如,短
)。但是,这是太麻烦所以为了清楚起见,你就要去说好
Convert.ToInt32(RDR [数量]);
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
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"]);