代码不在tabcontrol中的另一个选项卡上执行

时间:2019-05-09 14:43:10

标签: .net vb.net datagridview tabcontrol tabpage

嗨,我有点困惑我的代码没有在另一个选项卡上触发。 我有一个tabcontrol,上面有3个选项卡,每个选项卡都有一个datagridview。 每个标签的Datagridview1,2和3。

在datagridview1中,我有此代码。 这段代码将在datagridview1.cellclick上执行。

    Dim i As Integer
    Dim j As Integer
    For i = 0 To 50

        For j = 0 To 50

            If DataGridView3.Rows(i).Cells(1).Value = DataGridView2.Rows(j).Cells(0).Value Then
                DataGridView3.Rows(i).DefaultCellStyle.BackColor = Color.DarkSlateGray
            End If
        Next

    Next

如果我的datagridview3位于Tabpage3上,则此代码无法正常工作,但如果我将datagridview3置于Tabpage1上,则代码正常运行,则我选择的行将为灰色。我做错了吗?

1 个答案:

答案 0 :(得分:1)

尝试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