The wonderful DataGrid

Yes, I'm being sarcastic.

So, say you have a DataGrid. You have a set of items, and you want to be a good developer and databind those items to the grid. So far so good. Now, let's say that each item need a combobox because a cell value can have a limited sets of values. Fine, so you set up a data source for your items and a data source for your combobox column:

dataGrid.DataSource = viewModel.GridItems;
comboBoxColumn.DataSource = viewModel.ComboBoxItems;

Then you just make sure that the source column in your data grid has the same value as the Value member of your combobox column and you're pretty much home.

Now, the fun begins. Say that the data source in question needs different values in the combobox depending on the row. Not so fun anymore, eh?

The solution proved to be to bind the grid as usual, but avoid binding the combobox column. Instead, you subscribe to the DataBindingComplete event of the grid, wherein you apply some magic:

  int columnIndex = dataGrid.Column["ColumnInQuestion"].Index;
  for (int rowIndex = 0; rowIndex < dataGrid.Rows.Count; rowIndex++)
  {
    var comboBoxCell = (DataGridViewComboBoxCell)
      dataGrid[columnIndex, rowIndex];
    comboBoxCell.DataSource = viewModel.ComboBoxItems[rowIndex];
  }

Hope this helps,

/ Sami

Comments

Unknown said…
Or make a viewmodel where each row has a collection which holds the data for the combobox and lazy load that data. Works for WPF listviews at least.

/Frank

Popular posts from this blog

Auto Mapper and Record Types - will they blend?

Unit testing your Azure functions - part 2: Queues and Blobs

Testing WCF services with user credentials and binary endpoints