Tuesday, August 21, 2012

Problems With C# Datagrid Binding Combined With Combobox

Here’s an unexpected issue I ran into today that I am currently at a loss on how to solve. When you bind a DataGrid and a ComboBox to the same source and edit the items in the DataGrid you end up with a problem of the placeholder item in the DataGrid finding its way into the ComboBox . I haven’t found a solution yet which is irritating because I don’t need a problem like this finding its way into my system at this point especially. I HAVE TO DELIVER IT TOMORROW!!!!

I found the details of this problem on the WPF Toolkit Discussion board and the only useful information it provides me is to inform me that this is the result of a bad design decision on the part of the WPF team at Microsoft.

From the discussion board:

Hi superlloyd,

Ok, so it sounds like you've got your DataGrid and ComboBox bound to the same collection, and since the ComboBox doesn't know what to do with the NewItemPlaceholder, it crashes.  NewItemPlaceholder is something which we add to the DataGrid.Items collection to represent the blank AddNewRow in the DataGrid.  However, NewItemPlaceholder should not be added to the DataGrid.ItemsSource (just the Items collection), so if you bind your ComboBox to DataGrid.ItemsSource, then this should solve the problem.

If for some reason that doesn't work, a less elegant solution would be to have two separate collections, one for DataGrid (which includes the NewItemPlaceholder) and one for ComboBox (which does not).  Whenever anything is updated or added in the DataGrid's collection, you can manually make those same changes in the ComboBox's collection, which should give the same appearance to the end user of the editing the ComboBox's collection through the DataGrid.

Thanks!
Samantha

This is just a bad decision. I’ll probably dig around the DataGrid code later and see what I can do but it’s a pity given that it’s such an essential control. I’ll probably take the ugly and terrible approach of having a separate collection for the ComboBox because I need to get this done asap!

No comments:

Post a Comment