Introduction

This sample demonstrates how to bind a DataTable to a DataGrid, and how to work on the DataTable, with changes being reflected back in the DataGrid.

Building the Sample

Just download, unzip, open and run!

Description

This sample is in reply to a forum question about seeing changes in a DataGrid when changes are made to the underlying DataTable.

Firstly, the DataGrid's ItemsSource is bound to our DataTable.

XAML
Edit|Remove
<DataGrid ItemsSource="{Binding LogMessages}"/>

The "LogMessages" property is simply the DefaultView of the DataTable that we are working with:

C#
Edit|Remove
DataTable MyData; 
 
public DataView LogMessages 
{ 
    get { return MyData.DefaultView; } 
}
 For the purpose of this demonstration, create and populate the DataTable with one row of data:
C#
Edit|Remove
MyData = new DataTable(); 
MyData.Columns.Add("Col1"typeof(String)); 
MyData.Rows.Add("Pete");
This example uses the BackgroundWorker class to do the background thread work. An alternative is .Net4's Task class.
C#
Edit|Remove
    var bgw = new BackgroundWorker(); 
    bgw.RunWorkerCompleted += bgw_RunWorkerCompleted; 
    bgw.DoWork += bgw_DoWork; 
    bgw.RunWorkerAsync();
 
All we do in the background thread is add a row and pause. Three times:
C#
Edit|Remove
Thread.Sleep(1000); 
AddNewRow(DateTime.Now.ToString());
 
But the trick is to add the rows BACK on the UI thread, not from this background thread, so that change notifications fire on the correct thread, and the DataGrid's bindings know that they have to update:
C#
Edit|Remove
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => 
{ 
    MyData.Rows.Add(fakeRowData); // Add row on UI thread 
}));
When you run this project, you will see each row that has been added to the DataTable now shows being added to the DataGrid as well.

Source Code Files

Original forum question