Changing Combobox should update entity EF6

377 views Asked by At

So basically, I have an entity, I've used a LINQ query to get some items and bound that to a combobox.

What I'm trying to do is have the entity update when the item in the combobox is changed without doing a manual update in the Combobox.SelectedIndex/SelectedValue changed event. I'm just wondering if there is a better way?

Pseudo code:

SomeEntity se = new SomeEntity();
var q = from x in se select x;

cbComboBox.Datasource = q.ToList();
cbComboBox.DisplayMember = "SomeValue";
cbComboBox.ValueMember = "SomeValueID";
cbComboBox.SelectedValue = se.SomeValueID;

So the combobox shows the correct value I want. That's fine.

Here's the thing, when the user changes the combobox, I want se.SomeValueID to reflect that change.

I know I can set se.SomeValueID in the combobox SelectedValue event, but is there a better way? Where se.SomeValueID automagically gets updated?

2

There are 2 answers

2
cyberj0g On BEST ANSWER

Assuming your question is about Windows Forms. To bind SelectedValue to an object's property you can add custom binding:

cbComboBox.DataBindings.Add("SelectedValue", se, "SomeValueID");

That binding is two-way and there's no need in cbComboBox.SelectedValue = se.SomeValueID; line.

0
Arnel On

You should achieve this using Bindings defined in XAML instead of C# code behind code, here is an example:

 <ComboBox ItemsSource="{Binding SomeList}"
           DisplayMemberPath="SomeField"
           SelectedItem="{Binding CurrentItem, Mode=TwoWay}"/>

In this way you can have in your viewmodel class the list of entities (SomeList) and an object of the same type (CurrentItem) that will be updated every time the user change the selected item in the combobox. If you don't need the entire object, you can bind the selected value to a property exposed on your viewmodel with the same time of the id.

Hope this helps.