简体   繁体   中英

vb.net rebind datagrid to display changes in vb.net

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM