0

I have a product record table in the database, it will save the following: ID, product code, product name, size, and price. A product can have the same size and price right? In my code, I am trying to check if the data already exists, if it already exists it won't save but if not it will save. I already tried saving a different name and size of the product but with the same price but it would say that it already exists. I am new to c# and this is in WinForms, I searched it up here but I don't understand it and it is on other language. I only know java so far. I guess this error is a logical error, but I don't know what to do.

This is what I tried so far,

cmd = new SqlCommand("select Product_Code from ProductRecord where Product_Code = @Product_Code", con);
cmd.Parameters.AddWithValue("@Product_Code", tbpcCode.Text);
DataTable dt = new DataTable();
adapt.Fill(dt);
if ( dt.Rows.Count >= 1 )
{
  MessageBox.Show("Record Already Existing");
}
else
{
  // Do save
}
5
  • I suppose Product_Code is the PK, so the data won't be inserted if it's already there Commented Oct 6, 2019 at 12:43
  • ProductID is the primary key Commented Oct 6, 2019 at 13:00
  • 1
    You are only searching for product code. Not for product name, price or size. If the product code alrady exist you will always get Count>0 Commented Oct 6, 2019 at 13:02
  • Define a UNIQUE constraint on your table. Try to insert. Catch the exception. Commented Oct 6, 2019 at 13:48
  • I just define Product_Code as UNIQUE, now the database won't allow duplicate product codes. But I don't know what to change in my if statement or in the query? should it be select * from ProductRecord where Product_Code = @Product_code ? Commented Oct 6, 2019 at 14:10

1 Answer 1

-1

You don't have to open connection to the database each time you create a product. In fact you can rely on the Product_Code field in your database and change it to a unique key constraint see Microsoft docs here so its going to block the insertion of duplicate products.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.