我有一个DataGridView
我绑定到BindingSource
到DataView
到DataTable
。将行添加到DataTable
时,我希望更改自动显示在DataGridView
中,就像他们应该的那样。标准的东西。
如果我将DataTable
实例放在与DataGridView
相同的表单上,BindingSource
的{{1}}事件会触发,ListChanged
会刷新。但是,如果我将DataGridView
放在其他任何地方,例如在模块或其他表单中,DataTable
事件将不会触发,ListChanged
将不会自动刷新,除非我最小化并恢复它的形式。为什么呢?
更新
以下是我在一个简单的测试应用程序中执行此操作的示例:
模块:
DataGridView
表格:
Imports System.ComponentModel
Module modTick
Private WithEvents tmr As System.Timers.Timer
Private r As New Random()
Public dt As DataTable
Public Sub Init()
dt = New DataTable("table")
dt.Columns.Add("Number")
dt.Rows.Add(New Object() {r.Next})
dt.Rows.Add(New Object() {r.Next})
dt.Rows.Add(New Object() {r.Next})
End Sub
Public Sub StartTimer()
tmr = New System.Timers.Timer()
tmr.AutoReset = True
tmr.Interval = 500
tmr.Enabled = True
End Sub
Private Sub _tmrPulse_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles tmr.Elapsed
dt.Rows.Add(New Object() {r.Next})
End Sub
End Module
因此,如果我将模块的代码放在表单中,Public Class Form1
Private dv As DataView
Private WithEvents bs As BindingSource = New BindingSource()
Private WithEvents tmr As Timer = New Timer()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
modTick.Init()
dv = New DataView()
dv.Table = modTick.dt
dv.AllowDelete = False
dv.AllowEdit = False
dv.AllowNew = False
dgdisplay.AutoGenerateColumns = True
bs.DataSource = dv
dgdisplay.DataSource = bs
tmr.Interval = 500
tmr.Enabled = True
modTick.StartTimer()
End Sub
Private Sub tmr_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmr.Tick
Label1.Text = bs.Count
End Sub
End Class
会刷新,因为DataGridView
的{{1}}事件会触发。原样,既不会发火,也不会刷新。但是如果我最小化并恢复表单,则会发生变化。 BindingSource
显示ListChanged
中的项目数,这是正确的。