I'd like to deselect all selected rows in a DataGridView
control when the user clicks on a blank (non-row) part of the control.
How can I do this?
To deselect all rows and cells in a DataGridView
, you can use the ClearSelection
method:
myDataGridView.ClearSelection()
If you don't want even the first row/cell to appear selected, you can set the CurrentCell
property to Nothing
/null
, which will temporarily hide the focus rectangle until the control receives focus again:
myDataGridView.CurrentCell = Nothing
To determine when the user has clicked on a blank part of the DataGridView
, you're going to have to handle its MouseUp
event. In that event, you can HitTest
the click location and watch for this to indicate HitTestInfo.Nowhere
. For example:
Private Sub myDataGridView_MouseUp(ByVal sender as Object, ByVal e as System.Windows.Forms.MouseEventArgs)
''# See if the left mouse button was clicked
If e.Button = MouseButtons.Left Then
''# Check the HitTest information for this click location
If myDataGridView.HitTest(e.X, e.Y) = DataGridView.HitTestInfo.Nowhere Then
myDataGridView.ClearSelection()
myDataGridView.CurrentCell = Nothing
End If
End If
End Sub
Of course, you could also subclass the existing DataGridView
control to combine all of this functionality into a single custom control. You'll need to override its OnMouseUp
method similar to the way shown above. I also like to provide a public DeselectAll
method for convenience that both calls the ClearSelection
method and sets the CurrentCell
property to Nothing
.
(Code samples are all arbitrarily in VB.NET because the question doesn't specify a language—apologies if this is not your native dialect.)
C# version:
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
DataGridView.HitTestInfo hit = dgv_track.HitTest(e.X, e.Y);
if (hit.Type == DataGridViewHitTestType.None)
{
dgv_track.ClearSelection();
dgv_track.CurrentCell = null;
}
}
i found out why my first row was default selected and found out how to not select it by default.
By default my datagridview was the object with the first tab-stop on my windows form. Making the tab stop first on another object (maybe disabling tabstop for the datagrid at all will work to) disabled selecting the first row
Set
dgv.CurrentCell = null;
when user clicks on a blank part of the dgv.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With