将对象列表发送到另一个表单

Send list of objects to another form

我在 form1 中有一个 class 的对象列表。在 form2 中,我有一个列表框,需要用 form1 列表中的对象填充。这是小代码

public class Form1:Form
{
   public List<RegistrationInformation> car = new List<RegistrationInformation>();

   private void btnRegister_Click(object sender, EventArgs e)
   {
      //Create new object of class Registrationinformation which have created
      //new property like a Name, Surname, Car...

      RegistrationInformation c = new RegistrationInformation();
      c.Name= txtName.Text;
      c.Surname= txtSurname.Text;
      c.Car= txtCar.Text;
      car.Add(c); //Add object to list
      int number = car.Count; //this give me right result every next time
    }
}

public class Form2:Form
{
    //I tried this
    Form 1 frm = new Form1();
    listBox1.Items.AddRange(frm.car);

    //In this form I have some information about registered car and his owner
    //The left side of form is for listBox the right side is for some controls           
    //like is label, text box..When I select one item from list box I want to show information about them
    //So for that I tried with next code 

    int number = frm.car.Count; //But I find this problem - this give me result 0
    //So this code don't work
    if (number > 0)
    {
        for (int i = 0; i < number; i++)
        {
           string NameSurname = frm.car[i].Name + " " + rg.car[i].Surname;
           listBox1.Items.Add(NameSurname);
        }
    }
}

我在将对象列表中的项目添加到列表框时遇到问题。当我调用表 2 中的列表时,我得到的结果是他们没有项目。我在单击按钮时添加项目。因此,每次当用户更改 txtBox Name/Surname/Car 并单击 Button1 时,他们都会使用 属性 方法 Name、Surname、Car 创建一个 class 的对象。然后将对象放入列表。在第二个按钮上,我打开表格 2,我的屏幕就像我在评论中描述的那样 - listBox1.Items.AddRange(frm.car);

您是否知道第二个表单在列表中看不到项目的问题是什么?

更新: 我忘了补充说我创建了 Form1 的新实例并在表单加载时用它访问汽车列表我试图添加 [=24= 的构造函数] form2 但没有成功。

这是您第一个表单中的列表:

public List<RegistrationInformation> car = new List<RegistrationInformation>();

您在 btnRegister_Click 中单击按钮时将项目添加到该列表。

Form2 中创建 Form1 的实例并将其命名为 frm 并访问 car 列表。这个新表单 frm,没有人点击按钮,所以列表 car 是空的。因此,您没有得到列表中的任何项目。

问题出在变量的范围上。正如@CodingYoshi 所写,您在 Form2 中创建的 Form1 实例从未将任何汽车添加到列表中。

我建议您创建一个新的 class 来托管有问题的列表(可能作为一个单例,或者由 "main" 形式实例化)。这样,您就可以在 Form1Form2 之间共享列表。