i have a datagridview with 5 columns,when i press "enter" it goes to the next cell and when it arrives to the end of the rows when i press enter it adds a new rows,but my problem is when i move to the previous rows after i press enter it jumps the rows and does not go to the next cells,any help?
public partial class Form1 : Form
{
public static int Col;
public static int Row;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Rows.Add();
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
Col = dataGridView1.CurrentCellAddress.X;
Row = dataGridView1.CurrentCellAddress.Y;
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (int)Keys.Enter)
{
if (Col + 1 < 5)
{
dataGridView1.CurrentCell = dataGridView1[Col + 1, Row];
}
else
{
dataGridView1.Rows.Add();
dataGridView1.CurrentCell = dataGridView1[Col - 4, Row + 1];
}
}
}
}
Best Answer
Forget about CellEnter event and the Form1_KeyPress event also. Just handle the dataGridView1_KeyDown event like this:
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!