'datagridview values remove from another datagridview

I have two datagridviews. One is dtgridPopulate and is populated with data from the database.

dtgridPopulate columns are (checkbox, code, name)

checkbox code name
checkbox icon c1 customer_one

Then the second datagridview is dtgridGenerate which has generated values from dtgridPopulate. I use the code dtgridPopulate.Rows.Add(code, name) to add manually the value from dtgridPopulate to dtgridGenerate.

dtgridGenerate columns are (code, name)

code name
c1 customer_one

When I check the checkbox in the dtgridPopulate it will transfer the values (code, name) to the dtgridGenerate. But the problem is when I uncheck the checkbox in the dtgridPopulate, It should also REMOVE the values in the dtgridGenerate.

        Private Sub dtgridPopulateSelectAll_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As EventArgs) Handles dtgridPopulate.CurrentCellDirtyStateChanged

        RemoveHandler dtgridPopulate.CurrentCellDirtyStateChanged, AddressOf dtgridPopulateSelectAll_CurrentCellDirtyStateChanged

        If TypeOf dtgridPopulate.CurrentCell Is DataGridViewCheckBoxCell Then
            dtgridPopulate.EndEdit()
            Dim Checked As Boolean = CType(dtgridPopulate.CurrentCell.Value, Boolean)
            If Checked Then
                code = dtgridPopulate.CurrentRow.Cells(1).Value.ToString
                name = dtgridPopulate.CurrentRow.Cells(2).Value.ToString
                dtgridGenerate.Rows.Add(code, name)
            Else
               For Each drow As DataGridViewRow In dtgridPopulate.SelectedRows 'This is for uncheck but it doens't work
                    dtgridGenerate.Rows.Remove(row)
                Next
            End If
        End If

        AddHandler dtgridPopulate.CurrentCellDirtyStateChanged, AddressOf dtgridPopulateSelectAll_CurrentCellDirtyStateChanged
    End Sub

I refer to this reference

Error when I uncheck the checkbox: row provided does not belong to this datagridview control. parameter name: datagridviewrow



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source