views:

173

answers:

1

The easiest way I see to explain what I need is via example.

Suppose I have a DataGridView with 20 rows of data. The DGV is sized to show 10 rows at a time. It is scrolled to show rows 4-13. Row 7 is selected. What I need is a way to get that Row7 is the 4th displayed row.

+1  A: 

You can loop through all the DataGridViewRows in a DGV and check each Row's Displayed property. When you find the first one's that's true, that's your first displayed row. Continue looping and checking the Row's Selected property.

Here's some test code:

int foundRowIndex = 0;
bool foundFirstDisplayedRow = false;
foreach (DataGridViewRow row in dataGridView.Rows) {
    if (row.Displayed) {
        foundFirstDisplayedRow = true;
        Console.WriteLine(row.Cells[0].Value);
    }
    if (foundFirstDisplayedRow) {
       foundRowIndex++;
       if (row.Selected) {
          // You've got what you need here in foundRowIndex.
       }
    }
}

As a bonus, you can check the Displayed property of the 7th row to make sure the user didn't do anything crazy like size the DGV to stop displaying it.

Jay Riggs
That works. I was hoping their was a more direct way though.
Dan Neely