用于添加新行的数据网格视图按键事件

本文关键字:视图 事件 网格 数据网 添加 新行 数据 用于 | 更新日期: 2023-09-27 18:35:24

我有一个有 6 列的数据网格视图,每次按列的最后一个单元格上的"Tab"按钮(仅)时,我想添加一个新行,我使用下面的代码来防止每次写入单元格值时都添加行

dataGridView1.AllowUserToAddRows = false;
dataGridView1.Rows.Add();

我已经在单元格[5](最后一个单元格)上使用按键事件,但它不起作用,最后一个单元格设置为只读

private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (dataGridView1.CurrentCell.ColumnIndex == 5)
    {
        if (e.KeyChar == (char)Keys.Tab)
        {
            dataGridView1.Rows.Add();
        }
    }
}

谢谢你的时间,无论如何对不起我的英语

用于添加新行的数据网格视图按键事件

这将

添加一个Row当且仅当当前单元格是DGV中的最后一个单元格并且用户按Tab

请注意,(显然)用户现在无法跳出DGV,除非在第一个单元格上反向标记

int yourLastColumnIndex = dataGridView.Columns.Count - 1;
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (dataGridView.Focused && keyData == Keys.Tab) &&
        if (dataGridView.CurrentCell.ColumnIndex == yourLastColumnIndex
            dataGridView.CurrentRow.Index == dataGridView.RowCount - 1)
        {
            dataGridView.Rows.Add();
            // we could return true; here to suppress the key
            // but we really want to move on into the new row..!
        }
    return base.ProcessCmdKey(ref msg, keyData);
}

任何使用DGV的关键事件的尝试最终都会离开DGV,而不是添加Row