I am looking for a way to check if the DiscountCode value of my voucher item exists before creating a new database table row of the new voucher item. I've tried doing it with a few ways on my own previously but they didn't work for me and I am new to learning ASP.NET and C#.
How can I check and make sure the DiscountCode does not exist in the database table before creating a new row?
Here are the codes to create a new database row I have came up with.
public int VoucherInsert()
{
int result = 0;
string queryStr = "INSERT INTO Voucher(VoucherName,VoucherDescription,DiscountAmount,DiscountCode)" + " values (@Name,@Description,@Amount,@Code)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("@Name", this.Name);
cmd.Parameters.AddWithValue("@Description", this.Description);
cmd.Parameters.AddWithValue("@Amount", this.Amount);
cmd.Parameters.AddWithValue("@Code", this.Code);
conn.Open();
result += cmd.ExecuteNonQuery();
conn.Close();
return result;
}