Friday, 2 April 2010

DataGridViewComboBoxColumn and access modifiers

Despite my best efforts I’m still working on a Windows Forms project from a few months ago.  Apart from the fact that it’s helping me to appreciate WPF in a big way (particularly the way that modifying complex layouts is so much easier in XAML) it’s also raising issues that I should really be aware of by now.

One of these is that the data source for a DataGridViewComboBoxColumn’s list contents must have a public access modifier (assuming you’re binding to an IList).  This is so trivial I’m only mentioning it because it caused me a hour of grief last night trying to work out why my DataGridView wasn’t playing ball.  I wrongly assumed that I could use the internal access modifier and all would be well as long as the class was in the same project as the DataGridView.  Not so – as long as the fields being bound to the DisplayMember and ValueMember properties are public, then all is well (even if the class itself is internal).

For example, the following class:

internal class MyListSourceClass
public string Description {get;set;}
public string Value {get;set;}

Will bind quite happily in the following code:

List<MyListSourceClass> listSource = GetListDataFromSomewhere();

// where MyComboBoxColumn is the DataGridViewComboBoxColumn to be populated
MyComboBoxColumn.DataSource = listSource;
MyComboBoxColumn.DisplayMember = "Description";
MyComboBoxColumn.ValueMember = "Value";

but if we change the access modifiers on the Description and Value fields of MyListSourceClass then all sorts of nonsense happens.  I’m so looking forward to getting back to WPF.

No comments:

Post a Comment