DataGridView - 当我按下输入它进入下一个单元格

use*_*708 9 c# ado.net winforms

我有一个5列的datagridview,当我按"enter"它进入下一个单元格,当它到达行的末尾,当我按Enter键它添加一个新的行,但我的问题是当我移动到上一个我按下后输入它跳行,不会去下一个单元格,任何帮助?

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];
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Rei*_*ldo 11

忘记CellEnter事件和Form1_KeyPress事件.只需处理dataGridView1_KeyDown事件,如下所示:

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.Enter)
        {
            int col = dataGridView1.CurrentCell.ColumnIndex;
            int row = dataGridView1.CurrentCell.RowIndex;

            if (col < dataGridView1.ColumnCount - 1)
            {
                col ++;
            }
            else
            {
                col = 0;
                row++;
            }

            if (row == dataGridView1.RowCount)
                dataGridView1.Rows.Add();

            dataGridView1.CurrentCell = dataGridView1[col, row];
            e.Handled = true;
        }
    }
Run Code Online (Sandbox Code Playgroud)

请注意,我稍微更改了代码,并记得将Handled事件属性设置为true,否则它将处理默认行为.

干杯!