3

I have the following code that refreshes the datagrid in the form after the update is made to the database. My question is why do I have to clear the datasource and then re-add it to get the changes to display. I would think that the refresh method would do this, but I can't seem to get that to work. Is there a more efficient way to refresh the datagrid rather than resetting the datasource?

Public Sub addPlan(ByVal planname, ByVal plannumber)
    Dim planinfo As New changeDatabase(planname, plannumber, planAdapter)

    planinfo.addPlan()
    Form1.DataGridView1.EndEdit()

    Form1.DataGridView1.DataSource = ""
    Form1.DataGridView1.DataSource = planAdapter.GetData()
End Sub

2 Answers 2

5

Try creating an explicit BindingSource and assign a datasource to it, then set the DataGridView’s DataSource property to the BindingSource instance.

The BindingSource object’s ResetBinding method will cause the DataGridView to reread all the items in the list and refresh all displayed values.

Dim bindingSource As BindingSource
bindingSource = New BindingSource()
bindingSource.DataSource = planAdapter.GetData()
Form1.DataGridView1.DataSource = bindingSource

bindingSource.ResetBindings(false)

Note: Passing false means that only values have changed in the original datasource, true means that the schema of the data has changed.

1

The code below shows a way to set this up that works:

Protected WithEvents myWordClueList As WordClueList
Protected gridBindingSource As BindingSource

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    myWordClueList = New WordClueList()

    myWordClueList.Add(New WordCluePair With {.Word = "Eden", .Clue = "First garden"})
    myWordClueList.Add(New WordCluePair With {.Word = "Fears", .Clue = "Aggregate of negative emotions"})

    ' Instantiate a binding source for the GridView
    gridBindingSource = New BindingSource With {.DataSource = myWordClueList}
    WordClueGrid.DataSource = gridBindingSource

End Sub

The trick is to use a Binding Source object.

To update the GridView when changes are made to the DataSource, call the ResetBindings method of your BindingSource object.

        myWordClueList.OrderBy(Function(pairRow As WordCluePair) pairRow)
        gridBindingSource.ResetBindings(False)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.