如何从组合框中获取值以插入到Sql [英] How Can I Get Value From Combo Box To Insert To Sql
本文介绍了如何从组合框中获取值以插入到Sql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
SqlCommand cmd2 = new SqlCommand( insertProducts_TBL,con2);
cmd2.CommandType = System.Data.CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue( @ Product_name,txtProduct_name.Text);
cmd2.Parameters.AddWithValue( @ FK_catId,comboBoxFK_catid.SelectedValue);
解决方案
HI,我认为你的字段'FK_catId'是为什么会出现错误的int,所以你必须输入cast的combobox的字符串值如下所示整数,
Convert.Toint32(comboBoxFK_catid.SelectedValue)
完整代码如下:
SqlCommand cmd2 = new SqlCommand(insertProducts_TBL,con2);
cmd2.CommandType = System.Data.CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue(@ Product_name,txtProduct_name.Text);
cmd2.Parameters.AddWithValue(@ FK_catId,Convert.Toint32(comboBoxFK_catid.SelectedValue));
使用SelectedItem而不是
selectedValue
您的错误消息表明comboBoxFK_catid.SelectedValue
包含DataRowView
。您必须知道要在数据库中插入该行的哪一列 - 我在此处用columnName指示它,将其替换为实际的列名:
cmd2.Parameters.AddWithValue(
@ FK_catId,
((DataRowView )comboBoxFK_catid.SelectedValue)[ columnName]);
SqlCommand cmd2 = new SqlCommand("insertProducts_TBL", con2);
cmd2.CommandType = System.Data.CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("@Product_name", txtProduct_name.Text);
cmd2.Parameters.AddWithValue("@FK_catId", comboBoxFK_catid.SelectedValue);
解决方案
HI, I think your field 'FK_catId' is int that why error could arise ,so you have to type cast the string value of combobox into integer like this below,
Convert.Toint32(comboBoxFK_catid.SelectedValue)
Full code below:
SqlCommand cmd2 = new SqlCommand("insertProducts_TBL", con2); cmd2.CommandType = System.Data.CommandType.StoredProcedure; cmd2.Parameters.AddWithValue("@Product_name", txtProduct_name.Text); cmd2.Parameters.AddWithValue("@FK_catId", Convert.Toint32(comboBoxFK_catid.SelectedValue));
useSelectedIteminstead of
selectedValue
Your error message indicates thatcomboBoxFK_catid.SelectedValue
contains aDataRowView
. You have to know which column of that row you want to insert into your database - I indicate it here with "columnName", replace that with the actual column name:
cmd2.Parameters.AddWithValue( "@FK_catId", ((DataRowView)comboBoxFK_catid.SelectedValue)["columnName"]);
这篇关于如何从组合框中获取值以插入到Sql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文