1
7y

//not a rant
Ok so weird bug. Fellow C# people, help me out.

//already made it work so no I don't need to post it on SO

I write a Switch Case block based on the user's combo-box selection id.
if id 0, add everything to the mainpage grid
if 1, a foreach loop filtering out the ones with a certain attribute of the object as false and adding em to the grid on the mainpage
if 2, similar scenario as 1.
Countless times I had a null exception with the "count" variable being the number of items in the post which, wasn't null. there was no other variable that was being initialized from within the block, so I had no idea what was causing it.
Moving to an if-else statement doing the same thing, same issue.
In the end I created 2 empty lists before the switch case and filled them up and then another loop filling the mainpage grid with the now-filled list.
In the end im doing the same thing, with no issues, but I don't understand why adding it directly caused an error, what was null?
I wanna understand the working that might be causing this.. if anyone else came across this, would be glad to hear from you

Comments
  • 1
    Hard to tell without a piece of code to read. Are you sure che property you're testing when filtering is not null?
  • 0
    Threading issue?
  • 0
    I'd love to take a look at the code for you. Like ste09 said: hard to tell without
  • 3
    Talk is cheap, show me the code.
  • 0
    It's pretty hard to tell whats wrong with your code. You're writing that you add items to a "grid". What kind of a grid? DataGrid? As you mentioned, DataGrid.Items.Clear() should not throw errors. What exception occurs?

    But besides that, may I give you some general hints?
    You should take a look at DataBinding in WPF. Event driven UI stuff with code behind files is just hell. Binding the DataGrid to an ObservableCollection<> and adding an EventTrigger to the ComboboBox would make things a lot easier and cleaner :-)

    I would recommend you to review and follow some common C#.NET styleguides. Lowercase class names and uppercase private variables kinda hurt
    ;-P
  • 0
    @azuredivay Addressing your question about calling Wpgrid.Items.Clear() when the grid is empty causing a NullReferenceException. The problem here is that until you assign some kind of collection to the Items property, it's set to null as default. You can guard against that by using the ? operator wpgrid.Items?.Clear()
    How and where do you assign that wpgrid.Items property?
  • 0
    @ste09 Uhm...no. Look at ItemsControl implementation:

    https://referencesource.microsoft.com/...

    DataGrid.Items can't be null ;-)

    Add somewhere in XAML a <DataGrid x:Name="TestGrid"></DataGrid> and TestGrid.Items will return an empty ItemCollection.
  • 1
    @thoxx Thanks for the heads-up :) never really used Items directly, i usually set a databind on ItemsSource
Add Comment