system.data.sqlclient.sqlexception:'将nvarchar值转换为int数据类型时转换失败'

h22fl7wq  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(498)

我已经创建了一个数据库,我正在尝试 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();

当我运行它时,会出现以下错误:
system.data.sqlclient.sqlexception:'将nvarchar值'id'转换为数据类型int时转换失败'
我所有的 cbBox (组合框)需要留下 INT ,我明白需要转换为 NVARCHARINT ,我试着用 Convert.Into32(cbBox.Category.ValueMember) 但没有成功。
我什么都试过了,但没有成功。

oaxa6hgo

oaxa6hgo1#

在寻找其他人的答案后,我找到了这个解决方案。

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();

通过使用 Convert.ToInt32(cbBoxRoute.SelectedValue) 以下是我找到解决方案的链接:
将id从c#组合框插入sql

相关问题