Saturday, June 6, 2009

DataGridView EditMode EditProgrammatically

Problem: Whenever you want to write your own double click event for datagridview control, chances are, you will actually end up in edit mode. 

How to solve: DataGridView EditMode property.

From the MSDN,

DataGridView EditMode Property : Gets or sets a value indicating how to begin editing a cell.

The catch is:

All DataGridViewEditMode values except for EditProgrammatically also allow a user to double-click a cell to begin editing it.

Aha, that’s why the problem occur!! So, how do i use Edit EditProgrammatically?

MSDN give the following explaination:

Editing begins only when the BeginEdit method is called.

So I implemented the following event handler to call BeginEdit method.

private void dataGridView_ContextMenuViewEditCell(object sender, EventArgs e)

Then use contexmenu to register the event.

new ToolStripMenuItem(Resources.Common_Label_Edit, Resources.Image_16_Edit,
new EventHandler(this.dataGridView_ContextMenuViewEditCell)));

And finnally,  contexmenu only pop up when right click, so focus needs to be set, same as left click.

DataGridView.HitTestInfo hti = this.dataGridView.HitTest(e.X, e.Y);
if (hti.RowIndex >= 0 && hti.RowIndex < dataGridView.Rows.Count)
dataGridView.CurrentCell = dataGridView[hti.ColumnIndex,hti.RowIndex];

No comments: