Visual C# - 'Object reference not set to an instance of an object.' 尝试将列表传递给另一个表单时出错

Visual C# - 'Object reference not set to an instance of an object.' error when trying to pass a list to another form

不知道出了什么问题。该列表不为空,我以为我初始化了它。里面有项目,但如果程序不抛出空引用异常,我仍然无法将它传递给另一个表单。这是我的代码:

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();
            }
        }

结果表中的内容如下:

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
        }

我有一个类似的功能用于另一项任务并且它有效。这里出了什么问题?

当您尝试访问 null.

对象的字段或 属性 时,会抛出空引用异常

所以如果parent.resultsList抛出空引用异常,那是因为parentnull,也就是说this.Ownernull。这是因为您在调用 Show().

时没有传递 owner window

更改此行:

results.Show();

为此:

results.Show(this);