Wednesday, May 09, 2012 1:34 PM
I have encountered a BUG and reported it as per this link: https://connect.microsoft.com/VisualStudio/feedback/details/738820/setting-winforms-combobox-selectedvalue-throws-nullreferenceexception#details
I found the problem when binding a datatable to a ComboBox and trying to set the SelectedValue property to a valid value (NullReferenceException thrown). The problem occurs because the ValueMember points to a ColumnName that includes and '.' in it's name.
This means that if I use a DataAdapter to fill a dataset from a sql query like:
select 'Mr./Mrs.' as name+', '+lastname from customers
The dataAdapter will use 'Mr./Mrs.' and create a column with that name. If you bind this column as a DisplayMember to a ComboBox or ListBox, you will see it displayed as a DataRowView object. If you bind this column as a ValueMember and try to set the SelectedValue property to a valid value, it will throw a NullReferenceException.
In a system that allow people to write queries this will be an uncontrolled situation. My workarround is to encode the ColumnName if I detect a column with invalid characters in it. The documentation does not state that you can not use invalid characters in columnNames when binding, so the problem is not obvious to detect.
Also note that the exception is thrown at System.Windows.Forms.CurrencyManager.Find(PropertyDescriptor property, Object key, Boolean keepIndex)
This means that is a potential binding issue not only related to ComboBox or ListControl. Also note I tested this only in a winforms application, but I think a Wpf app can be affected by the same problem.
I have searched the web for people reporting this and found nothing, so I'm posting here. Does anyone think for a better workaround?