I'm running into a problem with databinding via BindingSource when the property of my business object has a value that does not exist in a bound list (say, a combobox).
For example, the form displays a list of states/regions; in this case the 50 U.S. states. My business object's .Region property has been initialized to a region not in that list, say Puerto Rico. I bind these together on a form so that the user can select a Region for the object.
When the .Region value exists in the list, the combobox is positioned to the correct value. However, as in this example, when the .Region value does not exist in the list, the combobox defaults to the first item, but the object is not updated accordingly. In this case, the screen is misleading: the combobox displays the first item in the list (AK - Alaska), but the underlying business object is still set to PR - Puerto Rico.
I've tried tapping the various events on BindingSource, checking for this condition and setting the object's value to the first value in the list. This works, but now I'm manually updating objects which questions databinding in the first place. I like databinding, but this breaks my trust when binding to lists.
Has anyone addressed this problem?
I thought the combo box should show nothing for the displayed value if the business object's property does not match a value in the list. I just did a quick test and that's how it behaves for me.
What I often do is have a "(Not selected)" display item in the combo box with a bound value of 0 or Guid.Empty or whatever is appropriate, and then on the business object initialise the property to this value, and validate it to say it's required. It forces the user to make a selection, which is sometimes a good idea, too.
Probably not the answer you were looking for, but it may help.
You are correct about the list positioning behavior. I added a line of code to manually set the list position (BindingSource.Find method) to the bound object's value. I presume the behavior you describe to be accurate.
What is the DataBinding UpdateMode on your ComboBox?
I'd assume you are using the default OnValidation but have you tried to change this setting to OnPropertyChanged? That should make sure the value is always in sync to the databound object.
Yes, you should use OnPropertyChanged, but the property on the business object still won't actually have a value pushed to it when there is no matching value in the combo box.
However, if you bind the combo box's data source after binding the data source for the business object, then it will clobber the biz object's property value with the first value in the list. (This is not usually the desired behaviour either.)
It might be that whether a CombBox will display values not in the list depends on the DropDownStyle. I can type a value not in the list if the value is DropDown, but not DropDownList. This might not be helpful in all cases depending on the underlying data mapping.
Copyright (c) Marimer LLC