0
votes

i have two datagridview in a form datagridview1 and datagridview2 and one button which named delete. Both datagridview 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 do not know how to do this? please tell me how to do this?

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
1
What is the DataSource of these Controls?Jimi
i am adding data from textboxes. DataGridView1.Rows.Add (textbox1.Text, textbox2Text, textbox3Text)pankaj babbar

1 Answers

1
votes

Remove the selected rows from DataGridView1 and the matches from DataGridView2 if any. The matches are identified by the Id column which is the first column in both DGVs. If that sounds right, then you can achieve that through a LINQ query as follows:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim q = From x In dataGridView1.SelectedRows.Cast(Of DataGridViewRow).
                Where(Function(r) Not r.IsNewRow),
                y In dataGridView2.Rows.Cast(Of DataGridViewRow).
                Where(Function(r) Not r.IsNewRow AndAlso
                    r.Cells(0).Value.ToString = x.Cells(0).Value.ToString).
                DefaultIfEmpty
            Select x, y

    For Each t In q
        dataGridView1.Rows.Remove(t.x)
        If t.y IsNot Nothing Then dataGridView2.Rows.Remove(t.y)
    Next
End Sub