tags:

views:

351

answers:

2

Is there a way to get the wpf toolkit datagrid to show new rows when its bound to a dataset? In other words, I have a datagrid, I've set its Itemssource to a DataTable, and everything seems to work fine, except I can't get the grid to show rows that I add to the DataTable programatically.

+1  A: 

You can set the datagrid.ItemsSource to an ObservableCollection<T>.

ObservableCollection<YourItem> items = new ObservableCollection<YourItem>();
yourDataGrid.ItemsSource = items;

Then you should be able to just add to the collection to get the new rows to appear:

Edit: Based on updated info.

if (Dispatcher.CheckAcces())
{
    // already on thread UI control was created on
    items.Add(<your item>);
}
else
{
    // update on same thread UI control was created on
    // BeginInvoke would invoke a delegate which would call items.Add(<your item>)
    Dispatcher.BeginInvoke(...);
}

See Dispatcher. All System.Windows.UserControl objects have a Dispatcher property.

Taylor Leese
Thanks for the suggestion. I've tried that, and when I use an observable collection, all the data in my grid is blank, and I still have the same problem.
Jonathan Beerhalter
Are the items you are adding to the ObservableCollection implementing INotifyPropertyChanged? The properties in YourItem need to match what is configured in the XAML. Perhaps if you post your code I could help more.
Taylor Leese
A: 

I'm not sure how anyone would have figured this out, especially since I didn't mention it, but the problem was that I was updating the dataset from a thread other than the form's main thread, i.e. the thread that the grid was created on. You can do updates from another thread, but you can't do inserts, although I don't know why. If someone could shed some light on that, I'd appreciate it. My guess would be that the grid checks to see if the insert is coming in on another thread, and if so, it ignores it because that would cause an exception.

Jonathan Beerhalter
See my updated response.
Taylor Leese
You should ALWAYS update controls from the thread they were created on. This isn't specific to anything with DataGrid.
Taylor Leese
But does updating a control extended to updating data that its bound to? When I was using the Xceed grid, this wasn't an issue, although perhaps Xceed took care of it behind the scenes.
Jonathan Beerhalter