Shmoopy Shmoopy - 3 months ago 16
C# Question

How to append data to DataGrid?

I have a

DataGrid
bound to a
DataTable
property.
The data is coming from the network in bulks.
Is there a way to tell
WPF
to append data to that grid without reloading the existing lines every time new data arrives?

I tried adding new rows to the
DataTable
and calling
DataGrid.Items.Refresh()
, but you can actually see the whole data gets reloaded every time new data arrives.

XAML:

<Grid>
<dg:DataGrid ItemsSource="{Binding MyDataTable} x:name="MyDataGrid"/>
</Grid>


C#:

void NewDataArrived()
{
foreach (var line in NewData)
{
MyDataTable.Rows.Add(line);
}
MyDataGrid.Items.Refresh();
}

Answer

If you bind your grid's DataSource to an ObservableCollection then when you add (or remove) items from that collection the grid will update for you.

Your XAML remains virtually the same:

DataSource="{Binding Results}"

But in your view model you have:

public ObservableCollection<DataType> Results
{
    get { ... }
    set { ... }
}

and when you read your data:

Results = new ObservableCollection(queryResults);