VBobCat VBobCat - 1 month ago 10
Vb.net Question

Prevent user from changing programmatical selection in DataGridView

I have a DataGridView whose rows are selected/unselected based on filters set through other controls. This selection is ment to be only programmatical. How can I prevent user from changing these selections?

Answer Source

I thought of answering by telling you to keep DataGridView1.Enabled = False, which may work as per your need, but you might lose some visual effects(like greyed-out DataGridView).

Setting DataGridView1.ReadOnly = True also won't help.

So the below code is not a perfect solution but more like a workaround to get exactly what you want (tested now & completely working):

Dim SelectedRows As List(Of DataGridViewRow) = New List(Of DataGridViewRow)

Private Sub DataGridView1_MouseDown(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseDown

    For Each Rows As DataGridViewRow In DataGridView1.SelectedRows
        SelectedRows.Add(Rows)      'Add all the rows pre-defined by your code
    Next

End Sub

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick

    DataGridView1.ClearSelection()  'clear the selection
    For Each rs As DataGridViewRow In SelectedRows
        rs.Selected = True          'restore the previous selected rows
    Next

End Sub

Private Sub DataGridView1_RowHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.RowHeaderMouseClick

    DataGridView1.ClearSelection()  'clear the selection
    For Each rs As DataGridViewRow In SelectedRows
        rs.Selected = True          'restore the previous selected rows
    Next

End Sub