Tuesday, May 20, 2008

GridView editing mode and BeginEdit()

The user can enter the edit mode on the GridView control by clicking (or double-clicking) on a cell or by typing a key matching a valid input character for the current cell.

The methods EndEdit() and CancelEdit() allow you to exit the editing mode pragmatically. A call to EndEdit() will trigger the validation of the cell currently editing while a call to CancelEdit() will discard the value inputted in the editing control.

Something which is missing in the GridView is the possibility to enter the edit mode explicitly using some code.

Here is a workaround I have found: simulate a user pressing a key on the grid by calling the OnKeyDown event handler. A point to consider is that you do not want that key event to modify the content of the cell once it switches to edit mode, therefore we must send a special key code which is not associated to a displayable character. I have found the sequence [Ctrl]-[Ins] to be suitable for this purpose:



public class MyGridView : GridView
{
public void BeginEdit()
{
if (RowCount == 0 || ColumnCount == 0) return;
if (IsCurrentCellInEditMode) return;
if (!ContainsFocus) return;
OnKeyDown(new KeyEventArgs((Keys)131168)); // Ctrl + NumPad0
}
}


Hope it helps,
Fred

No comments: