DataGridView-当我按 Enter 键时,它会转到下一个单元格

2023-11-26

我有一个包含 5 列的 datagridview,当我按“输入”时,它会转到下一个单元格,当它到达行的末尾时,当我按输入时,它会添加一个新行,但我的问题是当我移到上一个单元格时我按 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];
            }
        }
    }
}

也忘记 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;
        }
    }

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

Cheers!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

DataGridView-当我按 Enter 键时,它会转到下一个单元格 的相关文章

随机推荐