Reputation: 335
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.
Upvotes: 2
Views: 738
Reputation: 335
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.
Upvotes: 1