Chuck Wilbur
Chuck Wilbur

Reputation: 2620

How do I position a DataGridView to a specific row (so that the selected row is at the bottom)?

As a question similar to this question, I also have an application with a DataGridView on it. I would like to position the rows such that a specific row is at the bottom of the visible part of the list.

This is in response to a button click that moves a row down by one. I want to maintain the selection on the row I'm moving (I already have this part working). If there are lots of rows, the selected row might move below the visible area. I want to scroll down until it's at the bottom of the visible area.

There does not appear to be a LastDisplayedScrollingRowIndex companion to FirstDisplayedScrollingRowIndex.

Any ideas? Thanks.

Upvotes: 7

Views: 10640

Answers (2)

Chuck Wilbur
Chuck Wilbur

Reputation: 2620

As my own guess, I think I need to use FirstDisplayedScrollingRowIndex and the number of rows visible in the DataGridView to calculate the new FirstDisplayedScrollingRowIndex. Maybe I just need to find out what the NumberOfVisibleRows property is called?

Found it. DisplayedRowCount:

if (dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(false) <= selectedRowIndex)
{
    dataGridView.FirstDisplayedScrollingRowIndex =
        selectedRowIndex - dataGridView.DisplayedRowCount(false) + 1;
}

Code tested and working in my own project.

Upvotes: 9

Meta-Knight
Meta-Knight

Reputation: 17845

The DisplayedRowCount method will tell you how many rows are displayed on screen. Set the parameter value to true to include partial rows.

var displayedRows = myDataGridView.DisplayedRowCount(false);

Upvotes: 5

Related Questions