c#中的组合框项不能保存到数据库中
本文关键字:保存 数据库 不能 组合 | 更新日期: 2023-09-27 18:15:02
我有一个关于ComboBox
的问题。我有一个有2个项目的组合框。现在我想选择其中一个并将其保存到数据库中。但是在转换NVARCHAR值时,我有一个关于转换失败的错误。
转换nvarchar值时转换失败"System.Data。DataRowView'到数据类型int
我在数据库表中有一个字段,该组合框具有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();
}
}
}
}
}
您收到一个运行时错误:
转换nvarchar值时转换失败"System.Data。DataRowView'到数据类型int.
这是因为您试图使用组合框控件的SelectedItem
设置参数值。事实上,您的组合框的SelectedItem
是DataRowView
。如果您为那些ComboBox
控件设置了ValueMember
,则可以使用它们的SelectedValue
,否则您可以将SelectedItem
转换为DataRowView
并读取您想要的字段。例如:
var value = comboBox1.SelectedValue;
或
var value = ((DataRowView)comboBox1.SelectedItem)["Id"];
解决了…
cmd1.Parameters.AddWithValue("@FK_pro_id", (Convert.ToBoolean(cBoxProgram.SelectedValue = -1))? 0 : cBoxProgram.SelectedValue);