簡體   English   中英

選擇時在datagridview中選擇列標題和單元格的第一列

[英]Select column header and first column of a cell in datagridview when selected

當使用鼠標選擇一個或多個單元格時,我需要更改頁眉單元格和第一列“ col_row”的顏色,如下所示:

在此處輸入圖片說明

我使用此代碼及其工作方式:

    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

但是,例如,當我取消選擇第三列時,第一列會將其顏色更改為原始顏色。

在此處輸入圖片說明

我該如何預防呢?

謝謝!

您需要在更改Columns(e.Cell.ColumnIndex).HeaderCell.Style.BackColorRows(e.Cell.RowIndex).Cells("col_row").Style.BackColor之前檢查選定單元格的整個列和整個行Rows(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選擇/取消選擇單元格

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM