我有以下代码在更新数据库后刷新表单中的datagrid。我的问题是为什么我必须清除数据源然后重新添加它以获得要显示的更改。我认为刷新方法会这样做,但我似乎无法让它工作。是否有更有效的方法刷新数据网格而不是重置数据源?
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
答案 0 :(得分:5)
尝试创建显式BindingSource
并为其分配数据源,然后将DataGridView
的DataSource属性设置为BindingSource实例。
BindingSource
对象的ResetBinding
方法会导致DataGridView
重新读取列表中的所有项目并刷新所有显示的值。
Dim bindingSource As BindingSource
bindingSource = New BindingSource()
bindingSource.DataSource = planAdapter.GetData()
Form1.DataGridView1.DataSource = bindingSource
bindingSource.ResetBindings(false)
注意:传递false意味着原始数据源中只有值已更改,true表示数据架构已更改。
答案 1 :(得分:1)
下面的代码显示了一种设置方法:
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
诀窍是使用Binding Source对象。
要在对DataSource进行更改时更新GridView,请调用BindingSource对象的ResetBindings方法。
myWordClueList.OrderBy(Function(pairRow As WordCluePair) pairRow)
gridBindingSource.ResetBindings(False)