Wanabrutbeer
Wanabrutbeer

Reputation: 697

DataGridView Behavior

So, I am trying to rig a DataGridView so that when the enter key is pressed on the last cell of the last row, a new row will be added. I can't seem to get this to work, as the DataGridView controls don't seem to respond to any key events when enter key is pressed on the last row. Is there anyway to override this behavior?

Upvotes: 1

Views: 953

Answers (2)

Ashkan
Ashkan

Reputation: 2390

You can achieve this behavior like this:

    DataTable dt = new DataTable();
    int value = 0;
    private void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.AutoGenerateColumns = true;

        dt.Columns.AddRange(new DataColumn[]
            {
                new DataColumn("column1", typeof(string)),
                new DataColumn("column2", typeof(int)),
            });

        dt.Rows.Add("row " + value, value++);
        dataGridView1.DataSource = dt;
    }

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        DataGridViewCell cell = dataGridView1.SelectedCells[0];
        if (e.KeyCode == Keys.Enter && 
            cell.RowIndex == dataGridView1.Rows.Count - 1 && 
            cell.ColumnIndex == dataGridView1.Columns.Count - 1)
            dt.Rows.Add("row " + value, value++);
    }

this is a databinded gridview, of course you can add rows to an unbinded data grid view itself.

Upvotes: 0

JuStDaN
JuStDaN

Reputation: 449

protected override bool ProcessDataGridViewKey(KeyEventArgs e)
    {
        // Handle the ENTER key.  
        if (e.KeyCode == Keys.Enter)
        {
            // Add another if statement and use some logic to see if it is the cell you want then create your new row if true!
        }
        return base.ProcessDataGridViewKey(e);
    }

More info here: DataGridView.ProcessDataGridViewKey Method

Upvotes: 1

Related Questions