Click here to Skip to main content
15,905,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have two datagrid in a form datagridview1 and datagridview2 and one button which named delete. Both datagrid has some rows where first column "id" and second column "name" are same. I want if i delete a row from datagridview1 then it should automatically delete matching row in datagridview2.i am adding data from textboxes. DataGridView1.Rows.Add (textbox1.Text, textbox2Text, textbox3Text).i do not know how to do this? please tell me how to do this?

What I have tried:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    For Each rw As DataGridViewRow In DataGridView2.SelectedRows

        Dim x As String
        x = rw.Cells(0).Value
        For Each row As DataGridViewRow In DataGridView1.SelectedRows
            DataGridView1.Rows.Remove(row)
            If row.Cells(0).Value = x Then
                DataGridView2.Rows.Remove(row)
            End If
        Next
    Next
End Sub
Posted
Updated 20-Apr-20 7:15am
Comments
CHill60 20-Apr-20 12:36pm    
What is wrong with the code you have posted? What happens or doesn't happen?

Also, which is it - a datagrid or a datagridview?
relief122 20-Apr-20 12:37pm    
it is datagridview
Maciej Los 20-Apr-20 12:58pm    
Use "Reply" widget (on the right side of nick/login).

1 solution

I'd try something like this:

VB.NET
'for each row in DataGridView1; starting from the last one ;)
For i = DataGridView1.Rows.Count -1 To 0 Step -1
    'get specific row
    Dim srcRow As DataGridViewRow = DataGridView1.Rows(i)
    'find matched rows in DataGridView2
    Dim rowsToRemove = DataGridView2.Rows. _
        Cast(Of DataGridViewRow)(). _
        Where(Function(row) row.Cells("id").Value = srcRow.Cells("id").Value AndAlso row.Cells("name").Value = srcRow.Cells("name").Value). _
        ToList()
    'get the count of matched rows
    Dim x As Integer = rowsToRemove.Count
    'remove all matched rows from DataGridView2
    For Each dstRow In rowsToRemove
        DataGridView2.Rows.Remove(dstRow)
    Next
    'remove from DataGridView1 a row which had matched rows in DataGridView2
    If x>0 Then DataGridView1.Rows.Remove(srcRow)
Next


Note: above code has been written direct from my head... ;)
 
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