datagridview keypress事件用于添加新行

时间:2014-12-26 14:35:03

标签: c# datagridview row keypress

我有一个有6列的datagridview,我想每次按&#34时添加一个新行; 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();
        }
    }
}

感谢您的时间,对我的英语感到抱歉

1 个答案:

答案 0 :(得分:1)

当且仅当当前单元格是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 ..