Add BindingNavigator for DataGridView

To add a BindingNavigator for a DataGridView, even when there’s no DataSource like DataSet or DataTable in use, you can have DataGridView’s rows collection as DataSource for BindingSource.
And set that BindingSource to BindingSource property of BindingNavigator.

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles MyBase.Load

        BindingSource2.DataSource = DataGridView1.Rows
        BindingNavigator1.BindingSource = BindingSource2

        'instead of adding event handler for MoveFirst,MoveLast,MoveNext,MovePrevious
        'chose this one. it will fire anyway
        AddHandler BindingNavigatorPositionItem.TextChanged, AddressOf bindingnavigator_PostionChanged

    End Sub

    Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        BindingSource2.Position = e.RowIndex
    End Sub

    Private Sub DataGridView1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles DataGridView1.SelectionChanged
        If DataGridView1.SelectedRows.Count > 0 Then
            BindingSource2.Position = DataGridView1.SelectedRows(0).Index
        End If
    End Sub

    Private Sub bindingnavigator_PostionChanged(ByVal sender As Object, ByVal e As EventArgs)
        If CInt(BindingNavigatorPositionItem.Text) > 0 Then
            DataGridView1.ClearSelection()
            DataGridView1.Rows(CInt(BindingNavigatorPositionItem.Text) - 1).Selected = True
        End If
    End Sub
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s