Home > other >  Preventing duplicates when inserting data in gridview C#
Preventing duplicates when inserting data in gridview C#

Time:11-17

I have 2 tables, I need to copy the data of the parent table which is name (tblbenefit)" to another table (tbladdbenefit). So I need to retrieve and store the data of the parent table to the other table. And I also need to call it every time the form loads

the inserting part works, but the only problem I have is whenever the form loads, the table will insert along with the previous data I already displayed. So it will result in duplicate record whenever I open the form

So for example my parent table contains the values: value1 value2

The values are inserting to the new table, but whenever i close the form and reopened it, it will insert it again. Resulting in the table looking like:

value1 value2 value1 value2

Any Help would be appriciated!

I have tried this code

 con.Open();
        cmd = new SqlCommand("Insert into tbladdbenefit(Benefit, Amount) Select from tblbenefit",             con);
        cmd.ExecuteNonQuery();
        string query = "SELECT * FROM tbladdbenefit";
        SqlDataAdapter da = new SqlDataAdapter(query, con);
        DataSet ds = new DataSet();
        da.Fill(ds, "Employee Info");
        tbladdbenefit.DataSource = ds;
        tbladdbenefit.DataMember = "Employee Info";
        con.Close();
`

CodePudding user response:

Create a PrimaryKey and identify duplicates by comparing the PrimaryKey (GUID)

change

Insert into tbladdbenefit(Benefit, Amount) Select from tblbenefit

to

Insert into tbladdbenefit(Benefit, Amount, PrimaryKey) 
Select from tblbenefit 
where PrimaryKey not in (Select PrimaryKey from tbladdbenefit)

or an alternative approach (recommended)

 Delete From tbladdbenefit;
 Insert into tbladdbenefit(Benefit, Amount) Select from tblbenefit
  •  Tags:  
  • c#
  • Related