Claire
Claire

Reputation: 63

multiple selection on keyboard for datagridview c#

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#?

Upvotes: 3

Views: 1310

Answers (1)

OhBeWise
OhBeWise

Reputation: 5454

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.

Screen-shot of Keyboard selecting rows

Upvotes: 2

Related Questions