Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When I try to loop through the elements in a datagridview I'm getting an error "This row already belongs in the table". The error occurs at the add new row section of code. I have been struggling with this and cannot seem to find a solution. Could someone help? I'm sure it's just something simple that I am not seeing. Below is the code. Thanks in advance.



SELECT * FROM Testdat
da2 = New MySqlDataAdapter(sql2, conn2)
da2.Fill(ds2)
Dim cb As New MySqlCommandBuilder(da2)
Dim dsNewRow As DataRow
dsNewRow = ds2.Tables(0).NewRow
'Dim View As String
Dim i As Integer = 0
For Each row As DataGridViewRow In DataGridView1.Rows
dsNewRow.Item = DataGridView1.Rows(i).Cells(0).Value
'View = DataGridView1.Rows(i).Cells(0).Value
dsNewRow.Item( = DataGridView1.Rows(i).Cells(1).Value
dsNewRow.Item = DataGridView1.Rows(i).Cells(2).Value
i += 1
ds2.Tables(0).Rows.Add(dsNewRow) (error occurs here)
Next row
da2.Update(ds2.Tables(0))
Posted

I am lazy and I don't have time to create a project to test your code. By reading your code I can tell that you are not using the Item property of dsNewRow correctly.

There may be a primary key violation in here. You are trying to copy all the fields to the new row, resulting a new row to be identical to an existing row, which causes the error to be shown.
 
Share this answer
 
v2
put the line
VB
dsNewRow = ds2.Tables(0).NewRow
inside the for loop. It will be works. that's all
 
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