Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ComboBox.SelectedValue is null but .SelectedItem is not; SelectedValuePath is set. Why?

Debugging a strange NullRefException i see the following picture:

Double-shot to display .SelectedItem

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.

like image 369
Astrogator Avatar asked Oct 21 '22 01:10

Astrogator


1 Answers

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!! :)

like image 133
Astrogator Avatar answered Oct 23 '22 00:10

Astrogator