views:

1914

answers:

5

How to change the row position of virtual mode DataGridView?

I am using Windows Forms.

+2  A: 

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;

Marcus Erickson
Thanks, it changes the active row, it is highlighted. But it doesn't scroll on the new active row. e.g. grd.Rows[grd.Rows.Count-1].Selected = true, how to make datagridView scroll down to the active row?
Michael Buen
+1  A: 

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.

whatknott
I accept your answer as the correct one, it scrolls/brings the row into view if it isn't. Just the same, I also voted up Marcus' answer, I forgot to state in my question that the row needed be bring into view if it isn't. Yeah, dgv.CurrentCell = null is also needed
Michael Buen
A: 

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
A: 
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

it is really works only try this all others are fake

sudhir goyal
A: 

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.

Dav