I am using OleDB provider for Access database , developing in C# , VS2010
I have a Products table and Suppliers table
When I debug this code :
//open connection
con.Open();
//set command query for inserting a product
com2 = new OleDbCommand(@"INSERT INTO Products (ProductName,Model,Provider,Manufacturer,ReleasedDate,Quantity,SupplierID)
VALUES (@name,@model,@provider,@manf,@date,@quantity,@supp)", con);
/* ADDING PARAMETERS TO THE COMMMAND */
com2.Parameters.AddWithValue("@name", textBox1.Text);
com2.Parameters.AddWithValue("@model", textBox2.Text);
com2.Parameters.AddWithValue("@provider", textBox4.Text);
com2.Parameters.AddWithValue("@manf", textBox5.Text);
com2.Parameters.AddWithValue("@date", DbType.DateTime).Value = dateTimePicker1.Value;
com2.Parameters.AddWithValue("@quantity", Convert.ToInt32(textBox6.Text));
// com2.Parameters.AddWithValue("@price", Convert.ToInt32(textBox3.Text));
/* Getting the ID of the Supplier by his/her/it name and adding the value as a parameter */
com = new OleDbCommand("Select SupplierID from Suppliers WHERE SupplierName=@name",con);
com.Parameters.AddWithValue("@name",comboBox1.SelectedValue);
int str = (int)com.ExecuteScalar();
com2.Parameters.AddWithValue("@supp", str);
//INSERT EXECUTION
com2.ExecuteNonQuery();
MessageBox.Show("Product Added To Stock");
con.Close();
The program runs fine and executes the Query , but when i uncomment the line
com2.Parameters.AddWithValue("@price", Convert.ToInt32(textBox3.Text));
and Edit com2 Query string to :
com2 = new OleDbCommand(@"INSERT INTO Products (ProductName,Model,Provider,Manufacturer,ReleasedDate,Quantity,SupplierID,Price)
VALUES (@name,@model,@provider,@manf,@date,@quantity,@supp,@price)", con);
The program crashes at line com2.ExecuteNonQuery(); with this error:
You cannot add or change a record because a related record is required in table 'Suppliers'.
Notes:
- if you're wondering why I wanted to add Price, it's because I didn't add it from the first place
- The Price column exists in the table
Products - I deleted all the records in both tables
- Price column type : Number - Long Integer
- SupplierID is a primary key in Suppliers table
- While debugging,
strvalue was 4, which is the same value of one of the Suppliers
SupplierIDexists in theSuppliertable, because it is a foreign key, it appears.strvalue is 4 , which is the ID of one of the Suppliers