0
votes

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?

2
So you want to force the user to de-select row by row, right? - What about shilft-Selecting? Do you want it or not?TaW
I can compromise on that.Barry D.
Ha, that tells me - nothing. The problem I wanted to point to is: When you have shift-selection you can easily select many rows but won't have a way to deselect the easily.. - It is imperative to plan for the full set you want to implement!!TaW

2 Answers

0
votes

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.

0
votes

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.