2

i'm trying to set a cell to edit mode. The cell is in the new row (NewRowIndex). Everwhere else it works well, but if i try to set the edit mode in the NewRowIndex, it doesn't get into edit mode as supposed. I simply want that i f user enters a new row (NewRowIndex), the first cell get into edit mode. I've tried (on RowEnter):

dgvList.CurrentCell = dgvList["myColName", dgvList.NewRowIndex]; dgvList.BeginEdit(true);

Thank you!

FreewareFire
  • 33
  • 1
  • 1
  • 6
  • why are u first of all dealing with newrowindex at all? Just treat the new row as normal row and being edit – nawfal Oct 27 '12 at 10:05
  • what u mean with treat the new row as normal row? i'm dealing with newrowindex because only if user enters a new row, the edit mode should be triggered. may you post some code to show what u mean. thx! (ps. something like in Excel - if you press enter, cursor jumps to next row and if you start writing the cell enters edit mode) – FreewareFire Oct 27 '12 at 10:15
  • I already posted the code, see my second code block. In excel, if you press enter cursor only jumps to next row, it doesnt make the cell in edit mode. only when you begin to type it becomes in edit mode. So the you need not use dgv enter event at all.. – nawfal Oct 27 '12 at 10:26

1 Answers1

3

I dont think you really need to utilize the NewRowIndex property. Just begin edit by setting the current cell:

private void dgvList_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    dgvList.CurrentCell = dgvList[e.ColumnIndex, e.RowIndex];
    dgvList.BeginEdit(true);
}

If you want the cell to go in edit mode only for new rows, then:

private void dgvList_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex != dgvList.NewRowIndex)
        return;

    dgvList.CurrentCell = dgvList[e.ColumnIndex, e.RowIndex];
    dgvList.BeginEdit(true);
}

Edit: If you want the new row to start being in edit mode upon keydown, then that's a feature already available for datagridviews. You can manually set it like this:

dgvList.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
//or
dgvList.EditMode = DataGridViewEditMode.EditOnKeystroke;

If you want the cell to be in edit mode upon keydown only for new rows, then you will have to override the default behaviour, by hooking KeyDown event, which I believe is a bad way f doing GUI. May be like this:

Initialize: dgvList.EditMode = DataGridViewEditMode.EditOnF2; //or whatever you prefer

to override the default excel style editing upon keystroke. And then

private void dgvList_KeyDown(object sender, KeyEventArgs e)
{
    if (dgvList.CurrentCell.RowIndex != dgvList.NewRowIndex)
        return;

    dgvList.BeginEdit(true);
}
nawfal
  • 70,104
  • 56
  • 326
  • 368