I need to create a few keyboard shortcuts for a datagridview.
I need to allow the user to select multiple rows without using the mouse. e.g. in windows explorer you can:
Hold Ctrl (select first)
Up/down (move to next selection)
Space (select others).
Is this possible to do in C#?
Yes, it's possible. Because Ctrl+←→↑↓ already have default behaviors (such as navigating to the left-most, right-most, top-most, and bottom-most cells respectively), you'll have to inherit from the DataGridView class and override the ProcessDataGridViewKey method to handle these user actions as well as Ctrl+Space for selecting a row.
public class MultSelectKeyDGV : DataGridView
{
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
{
KeyEventArgs keyEventArgs = null;
DataGridViewSelectedCellCollection selectedCells = null;
bool selectRow = false;
if (e.Control)
{
switch (e.KeyCode)
{
case Keys.Down:
keyEventArgs = new KeyEventArgs(Keys.Down);
selectedCells = this.SelectedCells;
break;
case Keys.Up:
keyEventArgs = new KeyEventArgs(Keys.Up);
selectedCells = this.SelectedCells;
break;
case Keys.Right:
keyEventArgs = new KeyEventArgs(Keys.Right);
selectedCells = this.SelectedCells;
break;
case Keys.Left:
keyEventArgs = new KeyEventArgs(Keys.Left);
selectedCells = this.SelectedCells;
break;
case Keys.Space:
keyEventArgs = new KeyEventArgs(Keys.None);
selectRow = true;
break;
default:
keyEventArgs = e;
break;
}
}
else
{
keyEventArgs = e;
}
bool result = base.ProcessDataGridViewKey(keyEventArgs);
if (e.Control)
{
this.CurrentRow.Selected = selectRow;
this.KeepSelected(selectedCells);
}
return result;
}
private void KeepSelected(DataGridViewSelectedCellCollection selected)
{
if (selected != null && this.MultiSelect)
{
foreach (DataGridViewCell cell in selected)
{
cell.Selected = true;
}
}
}
}
Now just replace your instance of the DataGridView object in your Form with an instance of this class and you're done.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With