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.
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.
<DataGrid ItemsSource="{Binding LogMessages}"/>
<DataGrid ItemsSource="{Binding LogMessages}"/>
The "LogMessages" property is simply the DefaultView of the DataTable that we are working with:
DataTable MyData;
public DataView LogMessages
{
get { return MyData.DefaultView; }
}
DataTable MyData; public DataView LogMessages { get { return MyData.DefaultView; } }
MyData = new DataTable();
MyData.Columns.Add("Col1", typeof(String));
MyData.Rows.Add("Pete");
MyData = new DataTable(); MyData.Columns.Add("Col1", typeof(String)); MyData.Rows.Add("Pete");
var bgw = new BackgroundWorker();
bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;
bgw.DoWork += bgw_DoWork;
bgw.RunWorkerAsync();
var bgw = new BackgroundWorker(); bgw.RunWorkerCompleted += bgw_RunWorkerCompleted; bgw.DoWork += bgw_DoWork; bgw.RunWorkerAsync();
Thread.Sleep(1000); AddNewRow(DateTime.Now.ToString());
Thread.Sleep(1000);
AddNewRow(DateTime.Now.ToString());
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() =>
{
MyData.Rows.Add(fakeRowData); // Add row on UI thread
}));
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { MyData.Rows.Add(fakeRowData); // Add row on UI thread }));
