datagridview keypress event for adding new row

2019-07-21 08:23发布

i have a datagridview that has 6 column, i want to add a new row every time i press "Tab" button (only) on the last cell of the column, i used the code bellow to prevent adding row everytime i write cell value

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

i have already use keypress event on cell[5] (last cell) but it does not work, last cell was set to read only

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

thanks for your time, sorry about my english anyway

1条回答
爷、活的狠高调
2楼-- · 2019-07-21 09:06

This will add a Row if and only if the current cell is the last one in the DGV and the user presses Tab.

(Note that (obviously) the user now can't tab out of the DGV, except by backtabbing over the first cell..)

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);
}

Any attempt to use any of the Key events of the DGV will eventually leave the DGV instead of adding a Row..

查看更多
登录 后发表回答