Linq To Sql ComboBox (DropDownList) Setting Default Binding
We regularly setup simple winforms using Linq To Sql. I recently discovered that the ComboBox control when used as a DropDownList only updates the underlying databinding when it's clicked. So, if you tab into the control, hit the first letter to select your entry, then tab out. The underlying databinding never gets the new value. Linq set the binding property to the text value of ComboBox control as default.
开发者_C百科The fix for this was to change the linq binding value (thanks to commenter RedDog for pointing that out).
So my question is this: How do I set Visual Studio to make ComboBox automatically set bindingsource as SelectedItem as opposed to Text when dragging from Linq to Sql datasource? Saves work, sure, but also keeps bugs from finding their way to customers.
So, as per above, I believe you've resolved it by binding instead to SelectedItem
and ensuring that DataSourceUpdateMode
is set to OnPropertyChanged.
However, with the rephrased question, you'll find you can't change the VS behaviour. You'll have to make choices to what you bind to. There is a DefaultPropertyAttribute
out there that at least some of the designer listens to but I don't know if it works for binding.
I'll add that in our app we use a helper class to add all our bindings manually in code-behind rather than via the designer. This gives us a number of benefits including common behavioural "fixes" to all our bound controls. It also lets us use LINQ Expressions to resolve the property names and ensure that bindings are always to valid field names on the datasource - if setting bindings via the designer and then you delete a field in your schema then you won't know about the problem until run-time.
In the case of combo boxes our helper class had workarounds for:
- Always set
DataSourceUpdateMode
toOnPropertyChanged
- If bound to SelectedItem or SelectedValue:
- Then add a binding
Parse
event handler to reset the bound value to the bound type's default whenSelectedIndex
is -1 - When data source is changed for the combo box after binding is added then reset the
SelectedIndex
of the combobox (note, had to do more special stuff when bound toSelectedValue
for some reason)
- Then add a binding
精彩评论