2
votes

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.

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.

1
Are you bound to SelectedItem or SelectedValue? - Reddog
The Linq default when dragging field over from datasource it to bind to the Text value. I've tried that and SelectedValue. Both work, but only when clicking with mouse. If using keystrokes only, it never makes it back to the database. - RThomas
Ok, obviously I understood this wrong. I tried binding to SelectedItem and that does the trick. So, I'll update my question to how do I make default be to bind to SelectedItem and not Text. - RThomas

1 Answers

1
votes

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 to OnPropertyChanged
  • If bound to SelectedItem or SelectedValue:
    • Then add a binding Parse event handler to reset the bound value to the bound type's default when SelectedIndex 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 to SelectedValue for some reason)