datagridview keypress event for adding new row

限于喜欢 提交于 2019-12-11 02:54:57

问题


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:


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..



来源:https://stackoverflow.com/questions/27658408/datagridview-keypress-event-for-adding-new-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!