Question

How to change the row position of virtual mode DataGridView?

I am using Windows Forms.

Was it helpful?

Solution

Marcus's answer is correct, but you may also need to set the DataGridView's current cell property...

dgv.CurrentCell = dgv.Rows[0].Cells[0];

I believe this will scroll the grid. Also, to be absolutely safe, you may want to add this before the other line of code...

dgv.CurrentCell = null;

This will ensure that if the row you want is already the active row but just scrolled out of view, it will scroll it back into view.

OTHER TIPS

You have to clear the old position and set a new one

The collection dataGridView1.SelectedRows has the current selected Rows. Depending on the MultiSelect property of the grid you may have to loop through all the rows in the SelectedRows and mark them as unselected. If you are single selection mode, just setting the new row as selected should clear the old selection.

To select a particular row (in this case the one at index 0) you just add the line dataGridView1.Rows[0].Selected = true;

You seem to require not only setting the selected row, but also the displayed row. You can access the latter with the FirstDisplayedScrollingRowIndex property on your DataGridView. One of the useful setups:

int lastShown = FirstDisplayedScrollingRowIndex + DisplayedRowCount(false) - 2;

if (lastShown < yourIndex)
  FirstDisplayedScrollingRowIndex += yourIndex - lastShown;
else if (FirstDisplayedScrollingRowIndex > yourIndex)
  FirstDisplayedScrollingRowIndex = yourIndex;

will make sure your newly selected row does not disappear off the screen when scrolling up/down programmatically.

Else
        If i = rowcount Then
            Me.GridSaleItem.CurrentCell = Me.GridSaleItem.Rows(i - 1).Cells(0)
            Me.GridSaleItem.Rows(i - 1).Selected = True
        End If
    End If
Next
Private Sub GridSaleItem_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridSaleItem.SelectionChanged
    Dim rowcount As Integer
    rowcount = GridSaleItem.Rows.Count
    For i As Integer = 1 To rowcount
        If i = 1 Then
            '
        Else
            If i = rowcount Then
                Me.GridSaleItem.CurrentCell = Me.GridSaleItem.Rows(i - 1).Cells(0)
                Me.GridSaleItem.Rows(i - 1).Selected = True
            End If
        End If
    Next

End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top