4

Is it possible, out of the box, to sort a .NET DataGridView column using only the keyboard?

I understand there is a SelectionMode property, but changing this merely allows me to select, using Shift+Space, an entire row or column, but this doesn't have the same effect as clicking the header with the mouse and causing a sort.

The reason I ask is because I am working on accessibility issues and would like to avoid relying on the mouse.

Thanks for any assistance.

3
  • 1
    by "out of the box" do you mean "no code required"? Jul 5, 2011 at 20:28
  • Yes, sorry for the ambiguity, I was hoping there's a way to do this without code that I didn't know about.
    – Eric
    Jul 6, 2011 at 12:33
  • I don't think there is. The good news is that it shouldn't take very much code. =)
    – Stephen__T
    Jul 6, 2011 at 12:59

3 Answers 3

4

The first thing you will need to do is set the KeyPreview property to True in your form properties.

Then in the events you need to add an event handler for the KeyDown() event

Then add some code something like this:

public class Form1{
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);

private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        //sort column 0 descending on a 'D' press
        if (e.KeyCode == Keys.D)
            dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending);

        //sort column 0 Ascending on a 'U' press
        if (e.KeyCode == Keys.U)
            dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Ascending);
    }
}
1

May be I'm missing something, but call Sort method at the moment you receive desired Key combination.

0

i don't know that the column headers ever get focus (ctrl+tab/etc?), but if they could and your keyboard has a context menu button, that could work. but i don't think the headers ever get keyboard focus.

Otherwise, there may be ways to do it using standard accessability features?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.