Your sql insert text does not use parameters.
This is the cause of errors and worse (SqlInjection)
Change your code this way;
using(OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) { OleDbCommand cmd = new OleDbCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "insert into Items ([Item_Name],[Item_Price]) values (?,?); cmd.Parameters.AddWithValue("@item", itemNameTBox.Text); cmd.Parameters.AddWithValue("@price", Convert.ToDouble(itemPriceTBox.Text)); cmd.Connection = myCon; myCon.Open(); cmd.ExecuteNonQuery(); System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); }
Of course, this assumes that the text box for the price contains the correct numerical value.
To add this line before calling the code above
double price; if(double.TryParse(itemPriceTBox.Text, out price) == false) { MessageBox.Show("Invalid price"); return; }
then use price
as the value for the @price
parameter
** CHANGE 4 YEARS LATER **
This answer needs updating. In the above code, I use AddWithValue to add a parameter to the Parameters collection. This works, but every reader should know that AddWithValue has some disadvantages. In particular, if you find yourself on a simple path to add only rows when the destination column expects decimal values ββor dates. In this context, if I just wrote
cmd.Parameters.AddWithValue("@price", itemPriceTBox.Text);
the result could be a syntax error or some kind of weird value conversion, and the same thing could happen to dates. AddWithValue creates a Parameter row, and the database engine must convert the value to the expected column type. But differences in the locale between the client and server can lead to an incorrect interpretation of the value.
I think it's always better to use
cmd.Parameters.Add("@price", OleDbType.Decimal).Value = Convert.ToDecimal(itemPriceTBox.Text);
Additional information on AddWithValue Issues can be found here.