ListBox_Selection_Changed triggered by clearing its content

mauede

Well-known member
Joined
Sep 1, 2021
Messages
103
Location
Northwood - UK
Programming Experience
Beginner
When the user changes his/her mind and selects another item (a CT scan) of a ListBox, I need to erase the content of another three ListBoxes. I do that through the following statements:


C#:
StructSets.ItemsSource = null;
            StructSets.Items.Clear();
            StructSets.Items.Refresh();

where "StructSets" is the name of one of my ListBoxes.
To my dismay, the first statement triggers the "StructsSets_Selection_Changed" Event Handler that causes a
System.NullREferenceException because that code unit is not reached through the sequence of the expected steps
I need such an Event Handler to be triggered when the user selects a ListBox item clocking on it.
Should I use a different event for the code to be alerted when a ListBox item is selected through the mouse?
Thank you
 
If an item is selected and you clear the contents then that item is no longer selected, so of course a selection change is triggered and the appropriate event raised. The actual problem is that, in your code that handles that change, you're not testing to see whether an item is selected or not. You're just charging on ahead and using the current selection, which is null, and then being dismayed when a NullReferenceException is thrown. You need to validate the selection to make sure that it's not null before using it.
 

Latest posts

Back
Top Bottom