【发布时间】:2016-10-27 17:58:25
【问题描述】:
我对@987654321@ 有疑问。我有一个包含 2 个项目的组合框。现在我想选择其中一个并将其保存到数据库中。但是我在转换 NVARCHAR 值时遇到了关于转换失败的错误。
转换 nvarchar 值时转换失败 'System.Data.DataRowView' 到数据类型 int
我在数据库表中有一个用于该 ComboBox 的字段,该字段具有 VARCHAR(50) 数据类型。请解释一下为什么我出错了?这是代码
private void InsertCourseDetail()
{
if (string.IsNullOrEmpty(tbID.Text) == true)
{
CS = ConfigurationManager.ConnectionStrings["UMSdbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ISNULL(MAX(course_id),0)+1 FROM CourseDetail", con);
cmd.CommandType = CommandType.Text;
tbID.Text = cmd.ExecuteScalar().ToString();
{
using (SqlCommand cmd1 = new SqlCommand("INSERT INTO [dbo].[CourseDetail] (course_id,hec_code,course_type,FK_pro_id,course_cre_hour)VALUES(@course_id,@hec_code,@course_type,@FK_pro_id,@course_cre_hour )", con))
{
cmd1.CommandType = CommandType.Text;
cmd1.Parameters.AddWithValue("@course_id", tbID.Text);
cmd1.Parameters.AddWithValue("@hec_code", tbHECCode.Text);
cmd1.Parameters.AddWithValue("@course_type", (cBoxCourseType.SelectedItem == null) ? "NULL" : cBoxCourseType.SelectedItem.ToString());
cmd1.Parameters.AddWithValue("@FK_pro_id", (cBoxProgram.SelectedItem == null) ? "NULL" : cBoxProgram.SelectedItem.ToString());
cmd1.Parameters.AddWithValue("@course_cre_hour", (cBoxCreditHours.SelectedItem == null) ? "NULL" : cBoxCreditHours.SelectedItem.ToString());
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Has been Saved Successfully !", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
FillGridView();
}
}
}
}
}
【问题讨论】:
-
你得到什么错误信息。把它放在 try catch 中看看。
-
@PavanChandaka 将 nvarchar 值 'System.Data.DataRowView' 转换为数据类型 int 时转换失败。
-
我认为问题出在 cmd1.Parameters.AddWithValue("@FK_pro_id", (cBoxProgram.SelectedItem == null) ? "NULL" : cBoxProgram.SelectedItem.ToString());您在数据库中的“FK_pro_id”是 int 还是 integer 类型?
-
@PavanChandaka 使用此代码 cmd1.Parameters.AddWithValue("@FK_pro_id", (cBoxProgram.SelectedIndex == -1) ? 0 : cBoxProgram.SelectedValue);第一次保存记录但再次出错
-
你能告诉我错误是什么吗?