I need to change the color of the Header Cell and first column called "col_row" when one or more cells are selected with the mouse like this:
I use this code and its working:
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
but when i deselect, for example, the third column, the first column changes its color to the original color.
How can i prevent this?
Thanks!
You need to check the entire column and the entire row for selected cells before changing the Columns(e.Cell.ColumnIndex).HeaderCell.Style.BackColor
and the Rows(e.Cell.RowIndex).Cells("col_row").Style.BackColor
respectively.
Just because e.Cell.Selected
changed doesn't mean that it was the only cell forcing the column and row to be 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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.