Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move focus on next cell in a datagridview on Enter key press event

Friends, I'm working on windows application using C#. I'm using a datagridview to display records. The functionality I need is when I press "Enter" key the focus should go to the next cell(column of same row). If it's the last column in the grid then the focus should go to the first column of the next row. I've already tried using

    SendKeys.Send("{Tab}")

in datagridview1_KeyDown and datagridview1_KeyPress event. But focus is moving diagonally down. Please help me to solve this.

like image 858
Sukanya Avatar asked Mar 12 '12 12:03

Sukanya


Video Answer


2 Answers

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
    e.SuppressKeyPress = true;
    int iColumn = dataGridView1.CurrentCell.ColumnIndex;
    int iRow = dataGridView1.CurrentCell.RowIndex;
    if (iColumn == dataGridView1.Columncount-1)
    {
        if (dataGridView1.RowCount > (iRow + 1))
        {
            dataGridView1.CurrentCell = dataGridView1[1, iRow + 1];
        }
        else
        {
            //focus next control
        }
    }
    else
        dataGridView1.CurrentCell = dataGridView1[iColumn + 1, iRow];
}
like image 137
Kishore Kumar Avatar answered Sep 28 '22 03:09

Kishore Kumar


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;

    if (keyData == Keys.Enter)
    {                                
        if (icolumn == dataGridView1.Columns.Count - 1)
        {
            dataGridView1.Rows.Add();
            dataGridView1.CurrentCell = dataGridView1[0, irow + 1];
        }
        else
        {
            dataGridView1.CurrentCell = dataGridView1[icolumn + 1, irow];
        }
        return true;
    }
    else
        return base.ProcessCmdKey(ref msg, keyData);
    }
}
like image 40
Arun Agarwal Avatar answered Sep 28 '22 05:09

Arun Agarwal