无法在2个不同的列表框中显示2个不同的对象

时间:2019-11-28 06:02:38

标签: c# winforms

要事先弄清楚这是一项作业,如果我在做的事不好,我对此表示歉意,但这是所有条件的一部分。

WinForms能够处理2个listBox显示2个不同的对象数据时遇到了问题。我可以成功地将数据添加到listBoxes中的任何一个而没有和问题,但是一旦我尝试将数据添加到另一个中,就会遇到此错误。

System.NullReferenceException:'对象引用未设置为对象的实例。'

c为空。

Photo of Gui

        private void DisplayBook()//display method
        {
            //current index is equal to 0 and increments everytime an item is added ( max of 20)
            for (int i = 0; i < currentIndex; i++)
            {
                //Book is a class with getters and setters, myBooks is an array
                Book b = myBooks[i];
                //printbook is a print method on the Book class
                lstbook.Items.Add(b.Printbook());
            }               

        }

        private void DisplayCustomer()//display method
        {
            lstcustomer.Items.Clear();
            for (int i = 0; i < currentIndex; i++)
            {
                Customer c = myCustomer[i];
                lstcustomer.Items.Add(c.Printcustomer());
            }
        }

每个listBox的两种显示方法的示例。 我已经使用断点来尝试确定问题,但是一直很难捉摸,只在这两行上抛出了上述异常。

Customer c = myCustomer[i];
Book b = myBooks[i];

1 个答案:

答案 0 :(得分:0)

对于currentIndexCustomer,您似乎都使用相同的计数器(Book)。因此,当您先添加一个客户然后添加一个boox时,计数器将为2,但每个列表中只有一个。

要使显示对象更容易,请在两个对象上添加ToString方法的替代,因为这样我们可以将整个对象添加到列表框中:

public override string ToString() {
    return this.PrintBook(); // or this.PrintCustomer();
}

您可以将对象存储在列表中,而不必使用计数器:

IList<Customer> customers = new List<Customer>();

private void AddCustomer(Customer customer) {
    customers.add(customer);
}

然后我们可以使用foreach循环将所有项目添加到列表框中,但是由于我们已经在列表中包含了所有项目,因此我们可以将其设置为DataSource作为列表框:

lstcustomer.DataSource = customers;