-1

No clue what's wrong. The list is not null, I thought I initialized it. There were items in it, and yet I still can't pass it to another form without the program throwing a null reference exception. Here's my code:

public List<Global.Invoice> resultsList = new List<Global.Invoice>();

  private void stateComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool unique = true;
            resultsList.Clear();
            if (stateComboBox.SelectedItem.ToString() != SELECT_VAL)
            {
                foreach (Global.Invoice invoice in invoiceList)
                {
                    if (stateComboBox.SelectedItem.ToString() == invoice.recipientState)
                    {
                        foreach (int invoiceNo in invoiceNoListBox.Items)
                        {
                            if (invoice.number == invoiceNo)
                            {
                                unique = false;
                            }
                        }
                        if (unique == true)
                        {
                            resultsList.Add(invoice);
                        }
                        else
                        {
                            unique = true;
                        }
                    }
                }
                resultsForm results = new resultsForm();
                results.Show();
            }
        }

And here's what goes on in the results form:

private List<Global.Invoice> invoiceList = new List<Global.Invoice>();

  private void resultsForm_Load(object sender, EventArgs e)
        {
            mainForm parent = (mainForm)this.Owner;
            invoiceList = parent.resultsList; //null reference exception
        }

I have a similar function for another task and it works. What went wrong here?

AlexP98
  • 33
  • 3

1 Answers1

3

Null reference exceptions are thrown when you try to access a field or property of an object that is null.

So if parent.resultsList throws a null reference exception, it's because parent is null, which means that this.Owner was null. This is because you didn't pass an owner window when you called Show().

Change this line:

results.Show();

To this:

results.Show(this);
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84