Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm using datatable to insert records to my database in sql server and the reason why I'm using datatable is because the records to be inserted is on the datagridview. my question is, how can I check or validate records just in case I accidentally put duplicate records inside my datatable before saving it to the database. pls. help.thank you

What I have tried:

i have tried this but it still accepts duplicate records.

C#
SqlConnection connectionstring = connectionString.Getconnection();
SqlCommand command = new SqlCommand();
using (command = new SqlCommand("sp_Product_Name", connectionstring)//how to call stored proc with SELECT command
{
    CommandType = CommandType.StoredProcedure
})

   command.Parameters.AddWithValue("@SI_no", txtSalesInvNo.Text.Trim());
    command.Parameters.AddWithValue("@prod_name", data);
int foundrec = Convert.ToInt32(command.ExecuteScalar());

if (foundrec == 0)
{
    Save_SalesInvoice();
    foreach (DataGridViewRow row in dgvCustProducts.Rows)
    {
        dgvCustProducts.Rows[row.Index].SetValues(false);
        row.Cells[1].Value = 0;

    }
}

else
{

    MessageBox.Show("One of the Products already exist. Please Check the Records", "Duplicate Records", MessageBoxButtons.OK, MessageBoxIcon.Error);
    //txtSalesInvNo.Text = "";
   //txtSalesInvNo.Focus();

}
Posted
Updated 6-Jan-21 4:07am
v2
Comments
CHill60 31-Oct-20 6:44am    
It looks like you are already trying - what does the stored procedure do? Share that code
[no name] 31-Oct-20 10:50am    
You should never have a "duplicate" (sales) invoice; if invoice numbers are generated server-side.

1 solution

You didn't include query from SP. It's hard to guess without seeing that.

But you can prevent duplicates by using CONSTRAINT(For example SQL PRIMARY KEY Constraint[^] ) & checking existence of data(use SQL SELECT Statement[^] with WHERE clause before inserting row into database).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900