0

I have a datagridview named datagridview1 inculude a table from ms sql. I want to select a cell and then select another without unselecting the first cell that I have selected before. How can I do that?

I tried this code which is not selecting anything:

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
    If DataGridView1.CurrentCell.Selected = True Then
        DataGridView1.CurrentCell.Selected = False
    Else
        DataGridView1.CurrentCell.Selected = True
    End If

End Sub

Any suggestions?

Macukadam
  • 45
  • 2
  • 12
  • What is the point of the else? You would be setting the Selected property of the current cell to the same value it already is. It is not clear what you are trying to do here. – Sean Lange Feb 12 '16 at 14:39
  • I want to unselect if a cell is allready selected. Clicking a selected cell should unselect it. But whenever a cell is selected the other cells have selected before should remain selected as well. – Macukadam Feb 12 '16 at 14:41
  • Why not just use the Ctrl key which is standard in windows for multi-selecting cells. – Charles May Feb 12 '16 at 14:47
  • Well I could... But I don't want to use it everytime. The thing that I am trying to design should be very easy to use. I am sure there must be a solution. – Macukadam Feb 12 '16 at 14:49

1 Answers1

0

I guess then that you could roll your own datagridview and override the OnCellMouseDown and OnCellMouseUp events to give you this effect without the mouseup cancelling out the currently selected items.

Create a new class in your solution and inherit the datagridview

Public Class MyDataGridView
    Inherits DataGridView

    Protected Overrides Sub OnCellMouseDown(e As DataGridViewCellMouseEventArgs)
        Me.Rows(e.RowIndex).Cells(e.ColumnIndex).Selected = Not Me.Rows(e.RowIndex).Cells(e.ColumnIndex).Selected
    End Sub

    Protected Overrides Sub OnCellMouseUp(e As DataGridViewCellMouseEventArgs)
    End Sub
End Class

This should cancel out the what happens when the mouseclick event process fully which in a standard cell, will deselect the previous selection (unless the CTRL key is used).

Add this code, compile it and you should see at the top of your toolbox a MyDataGridView control. Drag it onto your form, populate it and give it a go.

Charles May
  • 1,725
  • 1
  • 11
  • 18
  • Thank you.. That is what I was looking for!! – Macukadam Feb 12 '16 at 15:12
  • Failed to load toolbox item 'MyDataGridView'. It will be removed from the toolbox. I am getting this error when trying to drag MyDataGridView control to my form. – Macukadam Feb 12 '16 at 15:34
  • I did a quick search on the error and found this [other SO topic](http://stackoverflow.com/questions/4800388/cannot-place-user-control-on-form). You might see if this applies to your application. – Charles May Feb 12 '16 at 16:09