Conversion failed when converting the varchar value 'System.Windows.Forms.ComboBox+ObjectCollection' to data type int

Multi tool use
Conversion failed when converting the varchar value 'System.Windows.Forms.ComboBox+ObjectCollection' to data type int
I began to show my DataGrid
on a form is created I would like when I course id
, rollno
. or enroll
no but when I execute this code than show the following problem:
DataGrid
id
rollno
enroll
Conversion failed when converting the varchar value 'System.Windows.Forms.ComboBox+ObjectCollection' to data type int
private void btnSubmit_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand(
"select COURSE_Id, ROLL_NO, ENROLL_NO, Sub_P_CODE, STUDENT_NA, th_a_o, th_b_o, th_c_o " +
"FROM annual_2018 " +
"where COURSE_ID = '" + course_id.Items.ToString() + "' " +
"and (ROLL_NO = '" + txtRoll.Text + "' OR ENROLL_NO = '" + TxtEnroll.Text + "')",
con);
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
Enroll_no.DataSource = dt;
con.Close();
}
And read this: stackoverflow.com/questions/25820944/…
– SehaxX
Jul 3 at 7:54
Welcome to Stack Overflow. :)
– aloisdg
Jul 3 at 7:54
Hi, I see you're new to SO. If you feel an answer solved the problem, please mark it as 'accepted' by clicking the gray check mark beside the answer. Check this link to know How does accepting an answer work: meta.stackexchange.com/questions/5234/…
– S.Akbari
Jul 3 at 10:11
1 Answer
1
You have passed the whole ComboBox
, you need to specify the SelectedValue
of your ComboBox
. Your COURSE_ID
column in the table is an int datatype and that is what you need to pass it. Also you should always use parameterized queries to avoid SQL Injection. Your code should be something like this:
ComboBox
SelectedValue
ComboBox
COURSE_ID
int selectedValue = Convert.ToInt32(course_id.SelectedValue.ToString());
cmd = new SqlCommand("select COURSE_Id, ROLL_NO, ENROLL_NO, Sub_P_CODE, STUDENT_NA," +
" th_a_o, th_b_o, th_c_o FROM annual_2018 where COURSE_ID = @courseId" +
" and (ROLL_NO = @ROLL_NO OR ENROLL_NO = @ENROLL_NO)", con);
command.Parameters.AddWithValue("@courseId", selectedValue );
//Other parameters
Although specify the type directly and use the Value
property is more better than AddWithValue
. See this Can we stop using AddWithValue() already?
Value
AddWithValue
cmd.Parameters.Add("@courseId", SqlDbType.Int).Value = selectedValue;
Obligatory reference: Can we stop using AddWithValue() already?
– Peter B
Jul 3 at 8:02
@PeterB Thanks. Yes, I was searching for that link also.
– S.Akbari
Jul 3 at 8:05
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
you can send just one value to COURSE_ID. It seems at it stands Items that here are more items and the ToString() will convert that to ObjectCollection not to the value you excpect.
– SehaxX
Jul 3 at 7:52