简体   繁体   中英

Handling Enter key in DataGridView

I have a datagridview having 5 columns. Columns in datagridview are [Item Code, Description, Quantity,Price & Total].

How it Should Work: When a user enters itemcode, the description and price should fetch from database and displays the result in respective fields. Then the quantity should be entered by user.

WHAT I WANT: I want when user enters value in 1st column(Item Code), the next cell to be selected should be the 3rd column(Quantity). Then if the quantity is entered and user presses the enter button, the next cell selected should be the 1st column(Item Code) of the next row.

PROBLEM: I have tried several codes but its not working. The problem is when an item code is entered in the 1st column(Item Code), the position of the next cell is the 2nd Row of the 3rd column(Quantity). It should move to the 3rd column(Quantity) of the same row ie the 1st Row .

Below is my code that I have used:

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
        currentRow = dataGridView1.CurrentCell.RowIndex;
        currentColumn = dataGridView1.CurrentCell.ColumnIndex;

    }

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {

        if (currentColumn == dataGridView1.Columns.Count - 5)
        {                
            dataGridView1.CurrentCell = dataGridView1[currentColumn + 2, currentRow];

        }
        else
        {
            dataGridView1.CurrentCell = dataGridView1[currentColumn - 2, currentRow + 1];
        }
    }

Thanks to this post.

I edited a little bit and here is my code which worked.

 protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
    {
        icolumn = dataGridView1.CurrentCell.ColumnIndex;
        irow = dataGridView1.CurrentCell.RowIndex;
        int i = irow;
        if (keyData == Keys.Enter)
        {
            if (icolumn == dataGridView1.Columns.Count - 5)
            {
                   dataGridView1.CurrentCell = dataGridView1[icolumn + 2, irow];
            }
            else
            {
                dataGridView1.CurrentCell = dataGridView1[icolumn - 2, irow + 1];
            }
           return true;
        }


        return base.ProcessCmdKey(ref msg, keyData);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM