Попробуйте событие RowPrePaint.
Private Sub DataGridView1_RowPrePaint(sender As Object, e As DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint
If e.RowIndex <= 50 Then
Dim DgvRow As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
For i As Integer = 0 To 50
If DgvRow.Cells(1).Value = DataGridView1.Rows(i).Cells(0).Value Then
DgvRow.DefaultCellStyle.BackColor = Color.DarkSlateGray
Else
DgvRow.DefaultCellStyle.BackColor = Color.Empty
End If
Next
End If
End Sub
Как бы я справился с этой ситуацией в строках, меньших, чем, скажем, 2000, - это создать источник привязки к источнику данных для datagridview2 и использовать метод Find.
IE:
'Declare a new bindingsource at Class scope
'Set its datasource to datatable used for DGV2
Dt2BindSource.DataSource = DtSet.Tables(1)
'Set bindingsource for DGV2 to bindingsource
DataGridView2.DataSource = Dt2BindSource
Private Sub DataGridView1_RowPrePaint(sender As Object, e As DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint
Dim DgvRow As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
Dim idx As Integer = Dt2BindSource.Find("Code", DgvRow.Cells("SubjectCode").Value.ToString)
If idx >= 0 Then
'Code exists
DgvRow.DefaultCellStyle.BackColor = Color.DarkSlateGray
Else
'Code no exist
DgvRow.DefaultCellStyle.BackColor = Color.Empty
End If
End Sub