C# 无法强制转换类型为';System.Int32';输入';System.String';错误

C# 无法强制转换类型为';System.Int32';输入';System.String';错误,c#,C#,我不断地犯这个错误。当该错误进入invoiceNum变量的while循环时,会发生此错误。你能告诉我我做错了什么吗 string selectSqlQuery = "SELECT * FROM Invoice"; //WHERE invoice_no=" + 1 + ""; //Create a command in C# to perform the sql Query SqlCommand mySelectCommand =

我不断地犯这个错误。当该错误进入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();
           }

要修复此错误,必须为整数调用
ToString
方法:

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

int i = 0;
string s = Convert.ToString(i);

将带有invoiceNum的行更改为:

invoiceNum = performCommand.GetInt16(0);

看起来,
invoiceNum
是一个32位整数,因此您必须使用reader的方法像读取一样读取它。阅读器不会在类型之间进行自动转换
GetString
仅当基础字段被键入为文本并且您遇到的强制转换错误正好告诉您:无法将整数转换为字符串时才起作用。请参见其中的备注部分,内容如下:

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

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

你应该重新写一行:

invoiceNum = Convert.ToInt16(performCommand.GetString(0));
改为:

invoiceNum = Convert.ToInt16(performCommand.GetInt32(0));
您应该根据正确的基础类型查看剩余的字段读取行


如果希望保持大部分代码不变,则应改为使用,因为这将返回一个
对象,其运行时类型将反映字段的类型。然后,您可以将其发送到一个
Convert
方法(正如您现在所做的那样),它将进行转换,假设它支持源类型和请求类型之间的转换。因此,只需将对读取器的所有
GetString
调用更改为
GetValue

invoiceNum变量定义和发票表定义中的第一列是什么?两者都是intI类型。我得到以下错误:System.InvalidCastException:指定的强制转换无效。当我将其更改为invoiceNum=performCommand.GetInt32时,它起作用(0);你为此苦苦挣扎了2个小时……非常感谢