Barry D.
Barry D.

Reputation: 547

How to multi-select and deselect rows in a DataGridView?

In short, the exact effect I'm trying to achieve is that of the following scenario:

You have a DataGridView with a couple of rows and the DataGridView.MultiSelect property set to true.

If you hold CTRL and click on rows, you can not only select rows, but even deselect the ones already selected - but you cannot do it without holding control.

How do I achieve a similar affect?

When I click on multiple DataGridView rows (individually), the DataGridView selections behaves as if the CTRL button is clicked.

If that is not possible (I've seen it on another project :() then how can it be made that DataGridViewRows are selected on one click, and deselected if not already selected?

Upvotes: 0

Views: 2994

Answers (2)

DeshDeep Singh
DeshDeep Singh

Reputation: 1843

You can try this simple workaround without having to modifying/inheriting DataGrid control by handling preview mouse down event as follows:

TheDataGrid.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(TheDataGrid_PreviewMouseLeftButtonDown);


void TheDataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    // get the DataGridRow at the clicked point
    var o = TryFindFromPoint<DataGridRow>(TheDataGrid, e.GetPosition(TheDataGrid));
    // only handle this when Ctrl or Shift not pressed 
    ModifierKeys mods = Keyboard.PrimaryDevice.Modifiers;
    if (o != null && ((int)(mods & ModifierKeys.Control) == 0 && (int)(mods & ModifierKeys.Shift) == 0))
    {
        o.IsSelected = !o.IsSelected;
        e.Handled = true;
    }
}

Method TryFindFromPoint is a borrowed function from this link http://www.hardcodet.net/2008/02/find-wpf-parent in order to get the DataGridRow instance from point you clicked

By checking ModifierKeys, you can still keep Ctrl and Shift as default behavior.

Only one draw back from this method is that you can't click and drag to perform range select like it can originally. But worth the try.

Upvotes: 0

Gnqz
Gnqz

Reputation: 3382

You could use a bool variable on the KeyDown and KeyUp events (of the main form) to check if CTRL is pressed and then process the row indexes from the CellContentClick or any other of the events (which passes the Row and Column index, which can be used to set the Selected property). Just do an if clause, which checks if the CTRL pressed bool variable is set and then do your stuff.

Upvotes: 0

Related Questions