[英]System.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value to data type int.'
I have creates a database and I am trying to INSERT INTO TABLE
with the following code:我已经创建了一个数据库,我正在尝试使用以下代码
INSERT INTO TABLE
:
string sqlquery = "INSERT INTO Runner VALUES (@firstName, @lastName, @amount, @category, @city, @charity, @route)";
cmd = new SqlCommand(sqlquery, conn);
conn.Open();
cmd.Parameters.AddWithValue("@firstName", txtFirstName.Text.ToString());
cmd.Parameters.AddWithValue("@lastName", txtLastName.Text.ToString());
cmd.Parameters.AddWithValue("@amount", Convert.ToInt32(txtMoney.Text));
cmd.Parameters.AddWithValue("@category", cbBoxCategory.ValueMember);
cmd.Parameters.AddWithValue("@city", cbBoxCity.ValueMember);
cmd.Parameters.AddWithValue("@charity", cbBoxCharity.ValueMember);
cmd.Parameters.AddWithValue("@route", cbBoxRoute.ValueMember);
cmd.ExecuteNonQuery();
conn.Close();
When I run it, I get this error:当我运行它时,我得到这个错误:
System.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value 'id' to data type int.'
System.Data.SqlClient.SqlException:“将 nvarchar 值 'id' 转换为数据类型 int 时转换失败。”
All my cbBox
(comboBox) need to leave a INT
, I understand that is need to convert to NVARCHAR
to INT
, I try to use Convert.Into32(cbBox.Category.ValueMember)
but without success.我所有的
cbBox
(comboBox) 都需要留下一个INT
,我知道需要将NVARCHAR
转换为INT
,我尝试使用Convert.Into32(cbBox.Category.ValueMember)
但没有成功。
I have tried everything with no success.我已经尝试了一切都没有成功。
After looking for other people answer I find this solution.在寻找其他人的答案后,我找到了这个解决方案。
string sqlquery = "INSERT INTO Runner (firstName, lastName, amount, categoryID, cityID, charityID, routeID) VALUES (@firstName, @lastName, @amount, @category, @city, @charity, @route)";
cmd = new SqlCommand(sqlquery, conn);
conn.Open();
cmd.Parameters.Add("@firstName", SqlDbType.VarChar, 50).Value = txtFirstName.Text;
cmd.Parameters.Add("@lastName", SqlDbType.VarChar, 50).Value = txtLastName.Text;
cmd.Parameters.Add("@amount", SqlDbType.Int).Value = txtMoney.Text;
cmd.Parameters.Add("@category", SqlDbType.Int).Value = cbBoxCategory.SelectedValue;
cmd.Parameters.Add("@city", SqlDbType.Int).Value = cbBoxCity.SelectedValue;
cmd.Parameters.Add("@charity", SqlDbType.Int).Value = cbBoxCharity.SelectedValue;
cmd.Parameters.Add("@route", SqlDbType.Int).Value = cbBoxRoute.SelectedValue;
cmd.ExecuteNonQuery();
MessageBox.Show("New Runner has been registered!");
conn.Close();
By using Convert.ToInt32(cbBoxRoute.SelectedValue)
通过使用
Convert.ToInt32(cbBoxRoute.SelectedValue)
Here is the link where I find my solution:这是我找到解决方案的链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.