In my WPF project I display data from a List of a class in a DataGrid. Every time the information from that list changes the DataGrid gets refreshed. This works correctly when a new item is added to the list, when an item changes and even works when an item is removed. However, when an item is removed it also generates a MessageBox type message stating that "Object reference not set to an instance of an object". The function seems to work entirely as intended, but I need this popup message to stop appearing.

private void VerwijderGezinButton_Click(object sender, RoutedEventArgs e)
{
    if (DataGridXML.SelectedIndex < 0)
        return;

    Gezin gezin = (Gezin)DataGridXML.SelectedItem;
    Gezinnen.Remove(gezin);
    DataGridPersonen.SelectedIndex = -1;

    DataGridXML.Items.Refresh();
    SaveToFile();
}

DataGridPersonen is a second DataGrid which displays a list of another class inside of individual item instances of the gezinnen List.

Gezinnen is assigned in the class like this

internal List<Gezin> Gezinnen { get; set; } = new List<Gezin> { };

Gezin is defined as such

[Serializable]
class Gezin
{
    public string Naam { get; set; }
    public string Prijs { get; set; }
    public int Kinderen { get; set; }
    public List<Volwassene> Volwassenen { get; set; }
    public Gezin(string naam, int aantalKinderen)
    {
        Naam = naam;
        Volwassenen = new List<Volwassene> { };
        Prijs = "n/a";
        Kinderen = aantalKinderen;
    }

    public void VoegVolwasseneToe(string naam, DateTime geboorteDatum)
    {
        Volwassenen.Add(new Volwassene(naam, geboorteDatum.ToShortDateString()));
    }
    public void VerwijderVolwassene(Volwassene persoon)
    {
        try
        {
            Volwassenen.Remove(persoon);
        }
        catch (Exception err)
        {
            MessageBox.Show("ERROR:\n\n" + err.Message);
        }
    }

}

and Volwassene

[Serializable]
class Volwassene
{
    public string Voornaam { get; set; }
    public string GeboorteDatum { get; set; }
    public Volwassene(string voornaam, string geboorteDatum)
    {
        Voornaam = voornaam;
        GeboorteDatum = geboorteDatum;
    }
}

When I use the debug mode of Visual Studio and run the code line by line this message appears exactly on DataGridXML.Refresh(); The variables themselves seem to change correctly when inspected in debug mode.

I need either to find a more extensive error message or a way to stop this message.

0 Answers