Reputation: 333
I have a DataGridView
in which I move from one cell to another whenever the ENTER key is pressed.
I have managed to find solutions for when the cell is in edit mode and not in edit mode.
The problem I'm facing is when the user is at the last row, while he is editing a cell and then presses ENTER, one event is not firing (selectionChanged
) and the cell does not leave focus. It just exits from edit mode. This is very strange because it only happens in the last row. All other rows are working as expected.
I am using 2 events in order to move to the next cell on Enter key while the cell is in edit mode.
private void dgvTT_SelectionChanged(object sender, EventArgs e)
{
if (MouseButtons != 0) return;
if (_celWasEndEdit != null && dgvTT.CurrentCell != null)
{
// if we are currently in the next line of last edit cell
if (dgvTT.CurrentCell.RowIndex == _celWasEndEdit.RowIndex + 1 &&
dgvTT.CurrentCell.ColumnIndex == _celWasEndEdit.ColumnIndex)
{
int iColNew;
int iRowNew = 0;
if (_celWasEndEdit.ColumnIndex >= colMaam.Index)
{
iColNew = colMisparHeshbon.Index;
iRowNew = dgvTT.CurrentCell.RowIndex;
}
else
{
iColNew = dgvTT.Columns.GetNextColumn(_celWasEndEdit.OwningColumn, DataGridViewElementStates.Displayed, DataGridViewElementStates.None).Index;
iRowNew = _celWasEndEdit.RowIndex;
}
dgvTT.CurrentCell = dgvTT[iColNew, iRowNew];
}
}
_celWasEndEdit = null;
}
private void dgvTT_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
_celWasEndEdit = dgvTT[e.ColumnIndex, e.RowIndex];
}
Any suggestions?
Upvotes: 0
Views: 5568
Reputation: 11
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
int iColumn = dataGridView1.CurrentCell.ColumnIndex;
int iRow = dataGridView1.CurrentCell.RowIndex;
if (iColumn == dataGridView1.Columns.Count - 1)
dataGridView1.CurrentCell = dataGridView1[0, iRow + 1];
else
dataGridView1.CurrentCell = dataGridView1[iColumn + 1, iRow];
}
}
catch { }
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataGridView1.Columns.Count - 1)
{
dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.CurrentRow.Index + 1].Cells[0];
}
else
{
SendKeys.Send("{UP}");
SendKeys.Send("{left}");
}
}
Upvotes: 1