14
votes

I have a DataGridView bound to a DB Table. The DataGridView is not editable, there are some text fields where the data can be edited, which is controlled with buttons. I have a NewRow Button with the following code:

        dataGridView1.AllowUserToAddRows = true;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Selected)
            { row.Selected = false; }
        } 
        dataGridView1.Rows[dataGridView1.NewRowIndex].Selected = true;

Wat I need is:

  • the datagridview should scroll to the bottom (where the newRow is)
  • the newRow should be focused, so that the textfields show the new (empty) row (content)

I've tried:

        bindSourceGS.Position = dataGridView1.NewRowIndex;

but that doesn't select the datagridview's newRow. I want to use the datagridview's newRow because when user presses cancel button I don't have to delete the row in the Dataset and the datagridview.Rows[i] has a IsNewRow Property.

3
don't mix DataGrid and DataGridView, they're different controls. I edited your question to make it clear you're using a DataGridView - Thomas Levesque

3 Answers

13
votes

If its Winform then you can use this

dataGridView1.FirstDisplayedScrollingRowIndex

and set the datagridview.CurrentCell to your new row cell address.

Hope this helps

0
votes

Note: For FirstDisplayedScrollingRowIndex to succeed if you have mixed-hieght rows, you need to ensure that Row Template height is at least as great at the last row height. This is rather a problem since I find one cannot set any row height greater than the Row Template height.

0
votes

I've been researching this problem and found that setting dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows.count-1 works well as long as the AutoSizeRowsMode property is NOT set to DisplayedCells.

If you have problems with setting dataGridView1.FirstDisplayedScrollingRowIndex=dataGridView1.Rows.Count -1 and the grid not scrolling to bottom try setting the AutosizeRowsMode property to AllCells.