Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Can';t在2个不同的列表框上显示2个不同的对象_C#_Winforms - Fatal编程技术网

C# Can';t在2个不同的列表框上显示2个不同的对象

C# Can';t在2个不同的列表框上显示2个不同的对象,c#,winforms,C#,Winforms,如果我所做的是一个糟糕的方式,我道歉,但这都是标准的一部分 WinForms无法处理2个列表框显示2个不同对象数据的问题。我可以成功地将数据添加到其中一个列表框中,而无需发出和,但只要我尝试将数据添加到另一个列表框中,就会遇到此错误 System.NullReferenceException:“对象引用未设置为对象的实例。” c是空的 您似乎对Customer和Book使用了相同的计数器(currentIndex)。因此,当您首先添加客户,然后添加boox时,计数器将为2,但每个列表中只有一项

如果我所做的是一个糟糕的方式,我道歉,但这都是标准的一部分

WinForms无法处理2个列表框显示2个不同对象数据的问题。我可以成功地将数据添加到其中一个列表框中,而无需发出和,但只要我尝试将数据添加到另一个列表框中,就会遇到此错误

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

c是空的


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

为了更容易显示对象,请在两个对象上为
ToString
方法添加覆盖,因为这样我们就可以将整个对象添加到列表框中:

public override string ToString() {
    return this.PrintBook(); // or this.PrintCustomer();
}
lstcustomer.DataSource = customers;
您可以将对象存储在列表中,这样就不必使用计数器:

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

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

我的对象上没有ToString方法。在它们各自的类中,我使用了一个公共字符串,它返回一个文本字符串并将该字符串打印到列表框中。我之所以这样做,只是因为这是为了一个任务,并且被要求以这种特定的方式来做。我将对此进行研究,但为了将来的使用,似乎更容易、更简洁。如果您需要使用代码,特别是for循环来解决它,那么您所要做的就是为每个循环使用一个唯一的计数器(而不是
currentIndex
您将拥有
currentBookIndex
等)。
public override string ToString() {
    return this.PrintBook(); // or this.PrintCustomer();
}
IList<Customer> customers = new List<Customer>();

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