选中时,在datagridview中选择单元格的列标题和第一列

时间:2015-09-11 12:56:05

标签: .net vb.net datagridview

我需要更改标题单元格的颜色和第一列名为" col_row"当使用鼠标选择一个或多个单元格时:

enter image description here

我使用此代码及其工作:

    Private Sub gdv_PatioAcopio_CellStateChanged(sender As Object, e As DataGridViewCellStateChangedEventArgs) Handles gdv_PatioAcopio.CellStateChanged
    If e.Cell.ColumnIndex = 0 Then
        e.Cell.Selected = False
    Else

        If e.Cell.Selected = True Then
            Me.gdv_PatioAcopio.Columns(e.Cell.ColumnIndex).HeaderCell.Style.BackColor = Color.LightBlue
            Me.gdv_PatioAcopio.Rows(e.Cell.RowIndex).Cells("col_row").Style.BackColor = Color.LightBlue
        ElseIf e.Cell.Selected = False Then
            Me.gdv_PatioAcopio.Columns(e.Cell.ColumnIndex).HeaderCell.Style.BackColor = Color.Navy
            Me.gdv_PatioAcopio.Rows(e.Cell.RowIndex).Cells("col_row").Style.BackColor = Color.Navy
        End If

    End If
End Sub

但是当我取消选择第三列时,第一列会将其颜色更改为原始颜色。

enter image description here

我该如何防止这种情况?

谢谢!

2 个答案:

答案 0 :(得分:2)

在分别更改Columns(e.Cell.ColumnIndex).HeaderCell.Style.BackColorRows(e.Cell.RowIndex).Cells("col_row").Style.BackColor之前,您需要检查选定单元格的整个列和整行。

仅仅因为e.Cell.Selected更改并不意味着只有 单元格强制列和行为Selected

Private Sub DataGridView1_CellStateChanged(sender As Object, e As DataGridViewCellStateChangedEventArgs) Handles DataGridView1.CellStateChanged
    If e.Cell.ColumnIndex = 0 Then
        e.Cell.Selected = False
    Else

        Dim rowSelected As Boolean = False
        Dim colSelected As Boolean = False

        For Each row As DataGridViewRow In Me.DataGridView1.Rows
            If row.Cells(e.Cell.ColumnIndex).Selected Then
                colSelected = True
                Exit For
            End If
        Next

        For Each cell As DataGridViewCell In Me.DataGridView1.Rows(e.Cell.RowIndex).Cells
            If cell.Selected Then
                rowSelected = True
                Exit For
            End If
        Next

        Me.DataGridView1.Columns(e.Cell.ColumnIndex).HeaderCell.Style.BackColor = If(colSelected, Color.LightBlue, Color.Navy)
        Me.DataGridView1.Rows(e.Cell.RowIndex).Cells("col_row").Style.BackColor = If(rowSelected, Color.LightBlue, Color.Navy)
    End If
End Sub

GIF selecting/deselecting cells

答案 1 :(得分:0)

Private Sub DataGridView1_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick

    DataGridView1.Columns(DataGridView1.CurrentCell.ColumnIndex).HeaderCell.Style.BackColor = Color.Gray

End Sub