For some reason result is always -1 and nothing get added to the database. I executed the query in SQL Server and it runs fine. I don't get any exception whatsoever and I don't use any stored procedure.
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=RAINBOW;Integrated Security=True"); SqlCommand cmd; cmd = new SqlCommand("INSERT INTO ItemDetails.item(description,category_id) VALUES (@item_desc,@cat_id)", con); cmd.Parameters.AddWithValue("@item_desc", txtitemdesc.Text); cmd.Parameters.AddWithValue("@cat_id", GetCategoryID()); try { con.Open(); int result = cmd.ExecuteNonQuery(); if (result > 0) { MessageBox.Show("Record Inserted Successfully!"); } else { MessageBox.Show("Failed to add record"); } } catch (SqlException ex) { MessageBox.Show("An error has occured! " + ex); } finally { con.Close(); } Edit
int GetCategoryID() { int cat_id = 0; cmd = new SqlCommand("SELECT category_id FROM ItemDetails.category WHERE category_desc=@cat_desc", con); con.Open(); cmd.Parameters.AddWithValue("@cat_desc", cboCategory.Text); reader = cmd.ExecuteReader(); while (reader.Read()) { cat_id = int.Parse(reader["category_id"].ToString()); } reader.Close(); con.Close(); return cat_id; }
AddWithValue()and add parameter like this -cmd.Parameters.Add("@item_desc", SqlDbType.VarChar, 1000).Value = txtitemdesc.Text;selectstatement it's a normal behavior because Forselectstatements, the return value ofExecuteNonQueryis-1but since your problem is withInsertyou should have no problem if you are sure thatGetCategoryID()andtxtitemdesc.Textcontain values and nothing else prevent the values to being inserted. Have a look at this answer: stackoverflow.com/a/32736842/2946329