0

I have 2 classes, Fleet and Car, a Fleet can have multiple Cars, both classes are ObservableCollections.

I made a button which has to delete the selected Fleet in a ListBox, when I click the button:

    private void btRemoveFleet_Click(object sender, RoutedEventArgs e)
    {
        Fleets.Remove((Fleet)lbFleets.SelectedItem);
    }

When I click the button in the following code the error occurs:

    private void lbFleets_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        Cars = ((Fleet)lbFleets.SelectedItem).Car;
        lbCars.ItemsSource = Cars;

        grdCarOverview.DataContext = Cars;
    }

     private void lbFleets_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        Cars = ((Fleet)lbFleets.SelectedItem).Car;
        lbCars.ItemsSource = Cars;

        grdCarOverview.DataContext = Cars;
    }

The error I get

System.NullReferenceException: 'Object reference not set to an instance of an object.'

I'm kind of new to C# and would just want to know what's going on and how to fix it.

sebas2201
  • 145
  • 3
  • 17
  • Where do you initialize "Fleets" ? – lucky Jan 23 '18 at 18:49
  • NullReferenceException means that an Object you are trying to access is null, in this case the problem seems to be in either Fleets or lbFleets.SelectedItem. Try logging them and see if they are null – Becks Jan 23 '18 at 18:50

0 Answers0