アプリケーション全体でアクセスできる共有/静的DataTableがあります。Formでは、DataGridViewがDataTableのDataViewにバインドされています。私の問題は、基になるデータソース (DataView) が更新されているにもかかわらず、 DataTableのクロススレッド更新がDataGridViewによってキャッチされないことです。
DataGridViewの update、invalidate、refresh、および resetbindings メソッドを試しましたが、まだ行が追加、削除、または更新されていません。
'The following example requires:
'-----------------------------------------------------------------------------
'Friend WithEvents DataGridView1 As System.Windows.Forms.DataGridView
'Friend WithEvents Button1 As System.Windows.Forms.Button
'Friend WithEvents Button2 As System.Windows.Forms.Button
'Friend WithEvents BackgroundWorker1 As System.ComponentModel.BackgroundWorker
'-----------------------------------------------------------------------------
Public Class Form1
Shared Sub New()
Repository = New DataTable()
End Sub
Public Sub New()
Me.InitializeComponent()
Me.view = New DataView(Repository)
Me.DataGridView1.DataSource = Me.view
End Sub
'Updates the DataGridView correctly.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Using table As DataTable = GetUpdatedDataTable()
SyncLock Repository
Repository.Merge(table)
End SyncLock
End Using
End Sub
'Do NOT update the DataGridView correctly (cross-thread)
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
If (Not Me.BackgroundWorker1.IsBusy) Then
Me.BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Using table As DataTable = GetUpdatedDataTable()
SyncLock Repository
Repository.Merge(table)
End SyncLock
End Using
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Me.DataGridView1.Update()
Me.DataGridView1.Refresh()
Me.DataGridView1.Invalidate(False)
Me.DataGridView1.Invalidate(True)
Me.DataGridView1.ResetBindings()
MsgBox(Me.view.Count)
End Sub
Private Shared Function GetUpdatedDataTable() As DataTable
Dim table As New DataTable("TEST")
table.Columns.AddRange(New DataColumn() {New DataColumn("ID", GetType(Integer)), New DataColumn("TEXT", GetType(String))})
table.Rows.Add(Repository.Rows.Count, String.Format("Row #{0}", Repository.Rows.Count))
table.AcceptChanges()
Return table
End Function
Public Shared Repository As DataTable
Private ReadOnly view As DataView
End Class'