Thursday, August 29, 2013

Alternative way to get latest selected value from a Combo Box

In .NET at times the ComboBox acts strangely, when you try to select a value but returns a null value (Though the value is displayed in the dropdown list). Using the following work around in the SelectedIndexChanged event or SelectionChangeCommitted event should do the needful.

foreach (Binding binding in (sender as ComboBox).DataBindings)
                {
                    binding.WriteValue();
                }

  var whateverObject = (sender as ComboBox).SelectedItem;

If anybody could explain on what cases a null could be returned, it would benefit many including me. Until that the above solution should save your day.