mani
mani

Reputation: 33

In Datagridview enter key press selection goes to next row but i want goes to next column?

In DataGridView enter key press selection goes to next row but I want goes to next column? How can fix it?

private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{       
   if (e.KeyCode == Keys.Enter)
   {
   }
}

Upvotes: 1

Views: 3901

Answers (1)

Artem Kulikov
Artem Kulikov

Reputation: 2296

There is a property named CurrentCell in the class DataGridView, so you should use it:

    private void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            int newRow;
            int newColumn;
            if (dataGridView1.CurrentCell.ColumnIndex == dataGridView1.ColumnCount-1)         // it's a last column, move to next row;
            {
                newRow = dataGridView1.CurrentCell.RowIndex + 1;
                newColumn = 0;

                if (newRow == dataGridView1.RowCount)
                    return; // ADD new row or RETURN (depends of your purposes..)
            }
            else                // just change current column. row is same
            {
                newRow = dataGridView1.CurrentCell.RowIndex;
                newColumn = dataGridView1.CurrentCell.ColumnIndex + 1;
            }

            dataGridView1.CurrentCell = dataGridView1.Rows[newRow].Cells[newColumn];
        }
    }

Upvotes: 1

Related Questions