pixelmeow pixelmeow - 2 years ago 360
Vb.net Question

Unselect/deselect row in DataGridView on click

I'm in the process of migrating VB6 code to VB.NET and we're up to the VS2013 stage, using .NET 4.5.2. In the original code, there are FlexGrids that allow row deletion on double-click and row selection/deselection on single click. I've got double-click going fine, it deletes the row and sets all rows as deselected (because double-clicking the header cell was re-ordering the rows and selecting a row, without a click on the row, and then deleting the now selected row). I don't know if that's relevant, but I've included it just in case.

I've looked here but it doesn't help because this behavior is expected and I don't know if the client will want to hear that everyone has to be re-trained to use the CTRL+click method to deselect. If that's how it must be, then so be it, but I have to try to make this work.

Using the cell click event to do something like this

Private Sub grdSelectedOps_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles grdSelectedOps.CellClick
If Not grdSelectedOps(e.ColumnIndex, e.RowIndex).Selected Then
grdSelectedOps(grdSelectedOps.CurrentCell.ColumnIndex, grdSelectedOps.CurrentCell.RowIndex).Selected = True

grdSelectedOps(grdSelectedOps.CurrentCell.ColumnIndex, grdSelectedOps.CurrentCell.RowIndex).Selected = False
End If
End Sub

doesn't work, because if you've clicked the cell you've selected it, so it always immediately deselects it. Multi-select is off. Is this possible?

Answer Source

Your Question is answered Here:

Toggle Selection in DataGrid

It is C# so here is the equivalent VB.NET Code is:

REM Keeps track of selection status
Private selectionChanged As Boolean

REM Fires Second
Private Sub dataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs)
    If Not selectionChanged Then
        selectionChanged = True
        selectionChanged = False
    End If
End Sub

REm Fires first
Private Sub dataGridView1_SelectionChanged(sender As Object, e As EventArgs)
    selectionChanged = True
End Sub

You may want to override the DataGrid Control to provide this functionality internally, but that is up to you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download