When I open my form that contains a DataViewGrid the first row is always automatically highlighted in blue showing that it is selected.
If I use

Me.DataGridView.ClearSelection()

the highlighting disappears and the row "appears" to be unselected but when I check with

Me.DataGridView.CurrentRow.Index the value returned indicates that the row is still selected, just the highlighting has disappeared.

What is the correct method to deselect a selection?........and
What is the correct method to check that a row has been selected?

(I am hoping to code a button that checks if a selection has been made, warn if not, then open an edit screen for the selected row)

Dani AI

Generated

noted that the visible blue highlight disappears but the grid still reports a current row; that is the key. The DataGridView keeps a "current cell" (the caret) separate from the selection state, so clearing only the visual selection leaves the current cell/row active. and were correct that removing the visual selection or moving focus affects the look, but the current position must be cleared after the data is bound.

Run the clear-after-binding logic (DataBindingComplete or the form's Shown event) and both clear any Selected flags on rows and remove the CurrentCell. Wrapping the CurrentCell assignment in a Try/Catch avoids errors when the grid is not ready.

Private Sub DataGridView1_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) _
    Handles DataGridView1.DataBindingComplete

    For Each r As DataGridViewRow In DataGridView1.Rows
        r.Selected = False
    Next

    Try
        DataGridView1.CurrentCell = Nothing
    Catch ex As InvalidOperationException
        ' ignore if current cell cannot be cleared yet
    End Try
End Sub

To check whether a row has been selected before opening an edit screen, use the SelectedRows or SelectedCells collections depending on SelectionMode. For full-row selection check SelectedRows.Count > 0; for cell selection check SelectedCells.Count and use SelectedCells(0).OwningRow to get the row. If MultiSelect is allowed, ensure exactly one row is chosen before opening the editor.

Recommended Answers

All 3 Replies

you can check selected row by using

DataGridView.CurrentRow.Index

you can deselect a row by using

'This should work 
Datagridview.ClearSelection()

'Try this if the first one doesn't work 
Datagridview.CurrentRow.Selected = false

Best thing to do is set the focus on another control in page load event.

'Unfortunately these methods do not deselect the Row Header
    Datagridview.ClearSelection()
     
    Datagridview.CurrentRow.Selected = false

    'And nor does moving the focus to another control
    'Any other ideas?
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.