DataGridView-当我按下回车键时它转到下一个单元格 [英] DataGridView-when I press enter it goes to the next cell

查看:26
本文介绍了DataGridView-当我按下回车键时它转到下一个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 5 列的 datagridview,当我按下enter"时,它会转到下一个单元格,当我按下 enter 时它到达行尾时,它会添加一个新行,但我的问题是当我移动时按回车键后到前一行,它会跳转行并且不会转到下一个单元格,有什么帮助吗?

i have a datagridview with 5 columns,when i press "enter" it goes to the next cell and when it arrives to the end of the rows when i press enter it adds a new rows,but my problem is when i move to the previous rows after i press enter it jumps the rows and does not go to the next cells,any help?

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 事件:

Forget about CellEnter event and the Form1_KeyPress event also. Just handle the dataGridView1_KeyDown event like this:

    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,否则会处理默认行为.

Please note that I changed the code a bit, and remember to set the Handled event property to true, otherwise it will process the default behavior.

干杯!

这篇关于DataGridView-当我按下回车键时它转到下一个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆