C# 将数据类型varchar转换为数字时出错。1-17-2014
我在插入记录时遇到问题,错误是“将数据类型varchar转换为数字时出错。” 这是我的代码集:C# 将数据类型varchar转换为数字时出错。1-17-2014,c#,sql,visual-studio-2010,C#,Sql,Visual Studio 2010,我在插入记录时遇到问题,错误是“将数据类型varchar转换为数字时出错。” 这是我的代码集: private void btnSearchCustomer_Click(object sender, EventArgs e) { //Get Customer Records DataSet dsCustomer = new DataSet(); dsCustomer = GetRecords("Customers"); frmBa
private void btnSearchCustomer_Click(object sender, EventArgs e)
{
//Get Customer Records
DataSet dsCustomer = new DataSet();
dsCustomer = GetRecords("Customers");
frmBasicSearch newSearch = new frmBasicSearch();
newSearch.myDataSet = dsCustomer;
newSearch.ShowDialog();
int myRowPosition = newSearch.myRowPosition;
if (myRowPosition != -1) //will display the value inside the textboxes
{
//concuntinated values
this.txtCustomerNo.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerNo"].ToString();
this.txtCustomerName.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerName"].ToString();
this.txtCustomerAddress.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerAddress"].ToString();
groupProduct(true); //this will activate the buttons from the Product Section
}
cn.Close();
cn.Open();
SqlCommand cmdInsert = new SqlCommand();
cmdInsert.Connection = cn;
cmdInsert.Transaction = trnOrder;
cmdInsert.CommandType = CommandType.Text;
cmdInsert.CommandText =
"INSERT INTO ShoppingCart " +
"(OrderDate, CustomerNo, CustomerName, CustomerAddress, PurchaseOrderNo, AgentNo, AgentName, InvoiceNo, TotalAmount, OrderStatus) " +
"VALUES ('" +
dtpOrderDate.Value.Date.ToString() + "', '" +
txtCustomerNo.Text + "', '" +
txtCustomerName.Text + "', '" +
txtCustomerAddress.Text + "', '" +
txtPONo.Text + "', '0', 'Agent', '" +
txtInvoiceNo.Text + "', '" +
lblTotal.Text + "', 'Void'); " +
"SELECT TOP 1 ShoppingCartNo FROM ShoppingCart " +
"ORDER BY ShoppingCartNo DESC;";
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
txtOrderNo.Text = nShoppingCart.ToString();
cmdInsert.ExecuteNonQuery();
cn.Close();
}
突出显示的部分是
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
我似乎不知道问题出在哪里?谢谢您的帮助。您可以在不使用Convert方法的情况下运行脚本吗。替换为: 字符串nShoppingCart=cmdInsert.ExecuteScalar().ToString() 然后看看nShoppingCart值是什么,看看它是否会转换成整数。我认为您在数据库数字字段中使用了“CustomerNo”字段,并且您正在尝试在该字段中插入varchar或string值,因为我可以看到您的代码,您将“txtCustomerNo.Text”放入其中,其中包含字符串值。您应该先将值转换为int或数据库字段中的任何值
希望这将对您有所帮助。尝试添加以下部分
Convert.ToInt16(lblTotal.Text)
那么什么是
cmdInsert.ExecuteScalar().ToString()
返回的?您确定“lblTotal.Text”包含正确的格式吗?(带“.”而非“,”)1。使用参数化SQL而不是动态构建SQL本身来传递值,以避免SQL注入。2.检查是否将非整数值插入整数字段。3.如果要将cmdInsert.ExecuteScalar().ToString()指定给textbox,为什么要将其转换为int?能否提供要插入的表架构?因为存在主模式,并且存在客户noi的自动增量,我认为发生此错误的原因是数据库列和输入中的数据类型不匹配。检查这些数据类型和输入类型是否完全匹配。customerno在主键中,IsIdentity属性是自动证明的