简体   繁体   English

处理DataGridView中的Enter键

[英]Handling Enter key in DataGridView

I have a datagridview having 5 columns. 我有一个有5列的datagridview。 Columns in datagridview are [Item Code, Description, Quantity,Price & Total]. datagridview中的列是[项目代码,描述,数量,价格和总计]。

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). 我想要什么:我想当用户在第1栏(物品代码)中输入值时,下一个要选择的单元格应该是第3列(数量)。 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). 问题是当在第1列(项目代码)中输入项目代码时,下一个单元格的位置是 3列的第2行 (数量)。 It should move to the 3rd column(Quantity) of the same row ie the 1st Row . 它应该移动到同一行的第 3列(Quantity), 即第1行

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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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