通过按下键在数据网格视图中添加行

Adding row in a datagridview by pressing down key

我想在 DataGridView 的最后一行按下 键在下方添加一行。

但我无法捕获按键按下或按键按下事件。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.AllowUserToAddRows = false;
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Down)
        {
            if (this.dataGridView1.Rows.Count > 0)
            {
                if (dataGridView1.CurrentRow.Index == (dataGridView1.Rows.Count - 1))
                {
                    dataGridView1.Rows.Add();
                    dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.RowCount - 1].Cells[0];
                }
            }
            else
            {
                dataGridView1.Rows.Add();
            }

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

}

我试过你的代码Eplzong。但是我现在不能使用向下键在行之间移动。

要从最后一行删除 * 使用 DataGridView 属性 AllowUserToAddRows = False.

并通过按下键在最后一行添加行试试这个:

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {  
        if (keyData == Keys.Down)
        {
            if(this.dataGridView1.Rows.Count > 0)
            {
                if (dataGridView1.CurrentRow.Index == (dataGridView1.Rows.Count - 1))
                {
                    dataGridView1.Rows.Add();
                }
            }
            else
            {
                dataGridView1.Rows.Add();
            }

            //selecting rows below current row
            if(dataGridView1.Rows.Count > 1)
            {
                dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.CurrentRow.Index + 1].Cells[dataGridView1.CurrentCell.ColumnIndex];
            }
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }