DataGridView-when I press enter it goes to the next cell
Try using this:
bool notlastColumn = true;
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
int icolumn = dataGridView1.CurrentCell.ColumnIndex;
int irow = dataGridView1.CurrentCell.RowIndex;
int i = irow;
if (keyData == Keys.Enter)
{
if (icolumn == dataGridView1.Columns.Count - 1)
{
//dataGridView1.Rows.Add();
if (notlastColumn == true)
{
dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0];
}
dataGridView1.CurrentCell = dataGridView1[0, irow + 1];
}
else
{
dataGridView1.CurrentCell = dataGridView1[icolumn + 1, irow];
}
return true;
}
else
if (keyData == Keys.Escape)
{
this.Close();
return true;
}
//below is for escape key return
return base.ProcessCmdKey(ref msg, keyData);
//below is for enter key return
return base.ProcessCmdKey(ref msg, keyData);
}
Just copy and paste the code.
Only thing you should have grid in your form.
Forget about CellEnter event and the Form1_KeyPress event also. Just handle the dataGridView1_KeyDown event like this:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
int col = dataGridView1.CurrentCell.ColumnIndex;
int row = dataGridView1.CurrentCell.RowIndex;
if (col < dataGridView1.ColumnCount - 1)
{
col ++;
}
else
{
col = 0;
row++;
}
if (row == dataGridView1.RowCount)
dataGridView1.Rows.Add();
dataGridView1.CurrentCell = dataGridView1[col, row];
e.Handled = true;
}
}
Please note that I changed the code a bit, and remember to set the Handled event property to true, otherwise it will process the default behavior.
Cheers!
this works for me
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
e.SuppressKeyPress = true;
int row = dataGridView1.CurrentRow.Index;
int col = dataGridView1.CurrentCell.ColumnIndex;
}
}