Wie kann ich die aktuelle Zelle in einem Datagridview markieren, wenn Selection = FullRowSelect
-
09-06-2019 - |
Frage
Ich habe einen bearbeitbaren Datagridview mit Selection zu FullRowSelect gesetzt (so wird die gesamte Zeile markiert ist, wenn der Benutzer klickt auf eine beliebige Zelle). Allerdings würde ich die Zelle wie das derzeit den Fokus hat mit einer anderen Hintergrundfarbe hervorgehoben werden (so kann der Benutzer klar sehen, welche Zelle sie im Begriff sind, zu bearbeiten). Wie kann ich dies tun (ich will nicht die selection ändern)?
Lösung
Ich fand heraus, einen besseren Weg, dies zu tun, das Cellformatting-Ereignis mit:
Private Sub uxContacts_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles uxContacts.CellFormatting
If uxContacts.CurrentCell IsNot Nothing Then
If e.RowIndex = uxContacts.CurrentCell.RowIndex And e.ColumnIndex = uxContacts.CurrentCell.ColumnIndex Then
e.CellStyle.SelectionBackColor = Color.SteelBlue
Else
e.CellStyle.SelectionBackColor = uxContacts.DefaultCellStyle.SelectionBackColor
End If
End If
End Sub
Andere Tipps
Für mich CellFormatting
funktioniert der Trick. Ich habe eine Reihe von Spalten, die man bearbeiten kann (die ich in einer anderen Farbe erscheinen gemacht), und dies ist der Code, den ich verwendet:
Private Sub Util_CellFormatting(ByVal Sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgvUtil.CellFormatting
If dgvUtil.CurrentCell IsNot Nothing Then
If e.RowIndex = dgvUtil.CurrentCell.RowIndex And e.ColumnIndex = dgvUtil.CurrentCell.ColumnIndex And (dgvUtil.CurrentCell.ColumnIndex = 10 Or dgvUtil.CurrentCell.ColumnIndex = 11 Or dgvUtil.CurrentCell.ColumnIndex = 13) Then
e.CellStyle.SelectionBackColor = Color.SteelBlue
Else
e.CellStyle.SelectionBackColor = dgvUtil.DefaultCellStyle.SelectionBackColor
End If
End If
End Sub
Sie wollen die Datagridview RowPostPaint Methode verwenden. Lassen Sie den Rahmen der Reihe ziehen, und danach zurückgehen und Farbe in der Zelle, die Sie interessiert sind.
Ein Beispiel ist hier unter MSDN
Versuchen Sie diese, die OnMouseMove Methode:
Private Sub DataGridView1_CellMouseMove(sender As Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseMove
If e.RowIndex >= 0 Then
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.SelectionBackColor = Color.Red
End If
End Sub
Private Sub DataGridView1_CellMouseLeave(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellMouseLeave
If e.RowIndex >= 0 Then
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.SelectionBackColor = DataGridView1.DefaultCellStyle.SelectionBackColor
End If
End Sub