سؤال

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!

هل كانت مفيدة؟

المحلول

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);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top