How to set focus to the last row in a DataGridView?

Viewed 820

enter image description here

How to set focus to the absolute last row?
I tried all the solutions I found in StackOverflow, but it always goes to the Row before the last, not the last one.

when I edit a value in the Quantity Column and press enter, I add two rows: the colored one which is read-only and also another row where I can add the next item.

Now, when I press Enter after typing the quantity, the focus goes to second row quantity: I need it to go to the first Column (Barcode) of the last row.

private void onCellEditEnd(object sender, DataGridViewCellEventArgs e)
{
   if(header == barcode)
    {
        dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value = item.Qty;
        dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value = item.Item;
        dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[3].Value = item.Mrp;
        dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[4].Value = item.Discount;
        dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[5].Value = item.Cgst;
        dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[6].Value = item.Sgst;
        dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[7].Value = item.Amount;

        dataGridView1.Rows.Add();
        dataGridView1.Rows[dataGridView1.CurrentRow.Index+1].Cells[1].Value = item.Details;
        dataGridView1.Rows[dataGridView1.CurrentRow.Index+1].Cells[4].Value = item.Discount;
        dataGridView1.Rows[dataGridView1.CurrentRow.Index+1].Cells[5].Value = item.Cgst;
        dataGridView1.Rows[dataGridView1.CurrentRow.Index+1].Cells[6].Value = item.Sgst;
            
        dataGridView1.Rows[dataGridView1.CurrentRow.Index + 1].ReadOnly = true;
        dataGridView1.Rows.Add();
    }
        dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2];
    }
    else if(header == quantity)
    {
        dataGrid.CurrentCell = dataGrid.Rows[2].Cell[0]; //tried this
        dataGridView1.Rows[dataGridView1.RowCount - 1].Selected = true; //tried this
    }
}

The second row is part of the first row, so on the CellEndEdit of Quantity I want the focus to go to the 3rd Row, in the Barcode Column, which I have added in the last line of code, using dataGridView1.Rows.Add();

2 Answers

To select a specific row you must use

dataGrid.Rows[index].Selected = true;

Wherever you make a change and you want the last row to be selected, you must use the following code :

dataGrid.Rows[dataGrid.RowCount - 1].Selected = true;

I had the same problem as you a couple weeks ago this is what I did.

    private void gridControl1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int indexOfRecent = gridView1.DataRowCount - 1;
                gridView1.FocusedRowHandle = indexOfRecent; 
            }
        }
Related