ComboBox SelectedItem vs SelectedValue Question

Annoying discovery of the day:

The following code works as you’d expect — MyProperty on the model is updated when the user picks a new item in the dropdown.

comboBox1.DataBindings.Add("SelectedValue", myModel, "MyProperty", true, DataSourceUpdateMode.OnPropertyChanged);

The following, however, doesn’t work the same way and the model update isn’t triggered until the input focus moves to another control on the form:

comboBox1.DataBindings.Add("SelectedItem", myModel, "MyProperty", true, DataSourceUpdateMode.OnPropertyChanged);

Does anybody know why? I’d investigate myself, but I don’t even know where to start. Pointers in the right direction to start the investigation or an outright explanation are both welcome.

Update: Some explanations are up on StackOverflow. In the end, I ended up binding to both SelectedValue and SelectedItem, which ensures instant model updates based on UI changes (through the SelectedValue binding), and UI updates based on programmatic model changes (through the SelectedItem binding).

Another thing to note is that when binding to SelectedValue without setting the DisplayMember/ValueMember properties, it helps to pass in “true” for the formattingEnabled binding parameter.

Advertisements
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: