Link to home
Start Free TrialLog in
Avatar of nikolaosk
nikolaoskFlag for Greece

asked on

How to use the keyboard to highlight rows in a DataGridView

hello experts,

i have developed an application in .net,WinForm  with C# .•¤ 2.0. i am returning through a DataGridView control records from a database in my form.

I need when ,for example, the user hits the "T" letter in the keyboard the first row in the DataGridView that starts with "T" to be selected.

i want the same behaviour that exists when we hit a letter in a windows explorer window and the first file-folder that starts with that letter is selected.

thanks a lot
Avatar of Marcus Keustermans
Marcus Keustermans
Flag of South Africa image

What you need to do here is to intercept the key down event  when the datagrid has focus and search for the respective row in the datagrid and select it.

You must however remember to manage this carefully as you do not want this to happen while editing a row. You can check this maybe by using IsCurrentCellInEditMode property and if it si you hande the key down event as such.
Avatar of nikolaosk

ASKER

can i get some code please?
H I am a bit pressed fo time right now.  Give me a day or two and  Iwill send you a code snippet.
thanks
any news? can anyone help?
Sory I forgot about the question.

Add the following event your datagrid.



 private void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            string c = ((char)e.KeyValue).ToString();
            bool firstRowSelected = false;
 
            while (!firstRowSelected)
            {
                if (!dataGridView1.CurrentCell.IsInEditMode)
                {
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        row.Selected = false;
                        if (row.Cells[0].Value != null)
                        {
                            if (row.Cells[0].Value.ToString().ToLower().StartsWith(c.ToLower()))
                            {
                                firstRowSelected = true;
                                row.Selected = true;
 
                            }
                        }
 
                    }
                }
            }
        }

Open in new window

If you want so select all the rows that start with the letter then you need to remove the firstRowSelected  bit.
Oops, forgot to mention that the grid needs to be readonly or editmode needs to be EditOnF2 and obviously the grid has to have focus.
ASKER CERTIFIED SOLUTION
Avatar of Marcus Keustermans
Marcus Keustermans
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks. it was helpful