如果DataTable不在同一表单上,则VB.NET BindingSource ListChanged事件不会触发

时间:2012-06-26 14:58:27

标签: vb.net data-binding

我有一个DataGridView我绑定到BindingSourceDataViewDataTable。将行添加到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中的项目数,这是正确的。

0 个答案:

没有答案