无法将类型为“System.Int32”的对象强制转换为“System.String”错误

时间:2016-06-11 23:28:51

标签: c#

我继续收到此错误。当它进入invoiceNum变量的while循环时会出现此错误。你能告诉我我做错了吗?

    string selectSqlQuery = "SELECT * FROM Invoice"; //WHERE invoice_no=" + 1 + "";
               //Create a command in C# to perform the sql Query
               SqlCommand mySelectCommand = new SqlCommand(selectSqlQuery, myDBconnection);
               //Creating the process for performing the command
               SqlDataReader performCommand = mySelectCommand.ExecuteReader();
               //Executing the command or running the command
             //  performCommand.Read();

               while (performCommand.Read())
               {

                   invoiceNum = Convert.ToInt16(performCommand.GetString(0));
                   pcBarcode = Convert.ToInt16(performCommand.GetString(1));
                   customerID = Convert.ToInt16(performCommand.GetString(2));
                   probDescr = performCommand.GetString(3);
                   empID = Convert.ToInt16(performCommand.GetString(4));
                   currentDate = Convert.ToDateTime(performCommand.GetString(5));
                   solution = performCommand.GetString(6); ;
                   partsID = Convert.ToInt16(performCommand.GetString(7));
                   labourPrice = Convert.ToInt16(performCommand.GetString(8));
                   totalPrice = Convert.ToInt16(performCommand.GetString(9));
                  // invoiceClass = new Invoice(invoiceNum, pcBarcode, customerID, probDescr, empID, currentDate, solution, partsID, labourPrice, totalPrice);
                }
               //Closing the execution of the command
               performCommand.Close();
               //Closing the connection
               myDBconnection.Close();
           }

3 个答案:

答案 0 :(得分:1)

将invoiceNum的行更改为:

invoiceNum = performCommand.GetInt16(0);

答案 1 :(得分:0)

要解决此类错误,您必须为整数调用8方法:

ToString

此外,如果您的类型实现int i = 0; string s = i.ToString(); ,您可以执行以下操作:

IConvertible

答案 2 :(得分:0)

看起来invoiceNum是一个32位整数,所以你必须使用读者的GetInt32方法读取它。读者不会在类型之间进行自动转换。仅当基础字段作为文本键入时,GetString才会起作用,并且您遇到的转换错误正好告诉您:无法将整数转换为字符串。请参阅GetString documentation的评论部分:

  

不进行转换;因此,检索到的数据必须已经是一个字符串。

     

在调用此方法之前,调用IsDBNull检查空值。

你应该重写这一行:

invoiceNum = Convert.ToInt16(performCommand.GetString(0));

改为:

invoiceNum = Convert.ToInt16(performCommand.GetInt32(0));

您应该根据正确的基础类型查看剩余的字段读取行。

如果您希望保持大部分代码相同,则应使用GetValue,因为它会返回object,其运行时类型将反映字段的类型。然后,您可以将其发送到Convert方法之一(就像您现在一样),并且它将执行转换,假设它支持源和请求类型之间的一个。因此,只需将阅读器上的所有GetString来电更改为GetValue

相关问题