按下键在datagridview中添加行

我想在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);
    }
上一篇:使用C#在Windows Form Application上从CSV文件读取和显示数据


下一篇:c#-DataGridView“索引-1没有值”