Wednesday, August 15, 2007

Turning off auto-scrolling in a bound DataGridView

I was running into an issue where I didn't want the grid to auto-scroll or change the selected row when the underlying DataSource property was changed. Here's what I came up with:

' dgv is a DataGridView control with SelectionMode set to FullRowSelect and MultiSelect set to False.
Dim intSelectedIndex As Integer = 0
If dgv.SelectedRows.Count > 0 Then
    intSelectedIndex = dgv.SelectedRows(0).Index
End If
Dim intDisplayIndex As Integer = dgv.FirstDisplayedScrollingRowIndex
' Set dgv.DataSource here
If intSelectedIndex < dgv.Rows.Count Then
    dgv.Rows(intSelectedIndex).Selected = True
    dgv.Rows(dgv.Rows.Count - 1).Selected = True
End If
If intDisplayIndex > -1 Then
    If intDisplayIndex <>
        dgv.FirstDisplayedScrollingRowIndex = intDisplayIndex
        dgv.FirstDisplayedScrollingRowIndex = dgv.Rows.Count - 1
    End If
End If

No comments: