Debugging a strange NullRefException i see the following picture:

So when the code is referring to .SelectedValue it crashes.
I cannot understand how .SelectedItem can be set, but .SelectedValue not. Values displayed in debugger's viewer are correct, .SelectedIndex is appropriate also. ComboBox's .ItemsSource is set to a List<DvcTypes> in code:
cbAdmDvc.ItemsSource = J790M.DAL.DvcTypes.GetList( );
.SelectedValuePath is set in XAML:
<ComboBox Name="cbAdmDvc" DisplayMemberPath="sDvcType"
SelectedValuePath="tiDvcType" SelectionChanged="cbAdmDvc_SelectionChanged".. />
Drop-down portion is properly displaying .sDvcType labels later on.
Very much the same implementation works for a bunch of other filtering combo-boxes (7 more).
This is happening during Loaded event for the main window.
So far i cannot explain the observed behavior, but found a relatively simple workaround:
private void cbAdmDvc_SelectionChanged( object sender, SelectionChangedEventArgs e )
{
if( cbAdmDvc.SelectedIndex < 0 ) return;
DvcType tiDvc; /// add this temp variable to capture .SelectedValue
if( cbAdmDvc.SelectedValue != null )
tiDvc= (DvcType) cbAdmDvc.SelectedValue;
else
tiDvc= ((DvcTypes) cbAdmDvc.SelectedItem).tiDvcType;
DoSmth( tiDvc ); /// instead of DoSmth( (DvcType)cbAdmDvc.SelectedValue )
}
Silly, but it works, since .SelectedItem is set properly.
As i said before, this is the only ComboBox experiencing such oddities out of several..
EDIT, 2014-Oct-21:
After making some changes in the application logic surprisingly found myself looking at the same issue with another ComboBox. Found a potential solution combobox-selectedvalue-not-updating-from-binding-source, but when i tried setting initial values via .SelectedItem instead of .SelectedValue things got even weirder/worse. So i tried to apply my previous solution here as well and it worked!
Here's my attempt to explain the observed behavior:
Setting an initial value in code (CBox.SelectedValue= smth;) triggers CBox_SelectionChanged event. For some reason at that moment reading .SelectedValue returns null (as if it's not ready yet), however reading .SelectedItem seems to work fine! Once you're out of CBox_SelectionChanged event code can read .SelectedValue properly..
So, if you 1) have a handler for _SelectionChanged event, 2) refer to .SelectedValue within it, and 3) are setting initial choice via .SelectedValue somewhere else in code - watch out for null and code defensively! HTH!! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With