2
votes

I'd be grateful for some help with the following.

I have a DataGridView form which has various text cells in it. Word wrap is enabled, so that the content of the cell wraps around if longer than the cell width, and the row height then adjusts automatically.

However, I want the user be able to easily edit the content of the cell. If there are lot of texts in the cell, the only way to go from one end to the other is to use the Right and Left cursor keys. If you press the Up and Down cursor keys, one would expect it to move to the next line within the same cell. But instead Up & Down keys change the Focus from current cell to the next adjacent cell.

Is there any way to override this behaviour so that when in edit mode, you can use Up, Down, Left and Right keys to navigate within the cell, not around it

I've tried various things but to no avail (e.g. editing the multiline property of the TextBox within the cell programmatically).

Any help would be much appreciated. Thank you.

1
Thanks for posting. Looking at that page, it seems to be dealing with how to skip specific cells when navigating around the DataGridView with the keys. I'm trying to stay within the current cell when using the keys - i.e. pressing the cursor keys moves you around the text in the current cell.Andrew17856
That is because being inside a cell, you are in it`s edit mode. Thus cursor keys would only move the selection cursor.boop_the_snoot
Sorry. In the original question, I say that when I use the cursor keys, it doesn't move around in the current cell, it moves to the next cell. Activating the cursor key's normal actions in the cell's edit mode is what I want to do.Andrew17856
I'm sorry i misread the question, tried reproducing the issue myself and yes I'm facing the same problem. Google doesn't seem to provide any viable results. After closing everything, I ended up on this link, try it at once.boop_the_snoot

1 Answers

1
votes

This is the problem: see here

The keypress events for the TextBox don't get fired because the arrow keys move to the next cell.

You therefore need to create a customised DataGridView and use that instead:

public class EditableDataGridView : DataGridView
{
    protected override bool ProcessDialogKey(Keys keyData)
    {
        Keys key = (keyData & Keys.KeyCode);
        if ( ( key == Keys.Up || key == Keys.Down ) && this.IsCurrentCellInEditMode )
        {
            return false; 
        }
        return base.ProcessDialogKey(keyData);
    }

    protected override bool ProcessDataGridViewKey(KeyEventArgs e)
    {
        if ( ( e.KeyCode == Keys.Up || e.KeyCode == Keys.Down ) && this.IsCurrentCellInEditMode )
        {
            return false;
        }
        return base.ProcessDataGridViewKey(e);
    }
}

Because the keyhandlers return false (i.e. the event isn't dealt with in the DataGridView) the keypress flows down to the TextBox itself.