【问题标题】:Send list of objects to another form将对象列表发送到另一个表单
【发布时间】:2016-12-31 01:40:07
【问题描述】:

我在 form1 中有一个类的对象列表。在 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 创建一个类对象。然后对象被放入列表。在第二个按钮上,我打开表格 2,然后我看到了我在评论中描述的屏幕 - listBox1.Items.AddRange(frm.car);

您可能知道为什么第二种形式在列表中看不到项目是什么问题?

更新:我忘记添加我创建 Form1 的新实例并在表单加载时使用它访问汽车列表我试图添加我的类 form2 的构造函数但没有成功。

【问题讨论】:

  • 您可以通过多种不同的方式做到这一点:使用构造函数、使用对象、使用属性、使用委托。这是一篇不错的文章--> passing data between forms

标签: c# .net list listbox add


【解决方案1】:

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

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

当单击btnRegister_Click 中的按钮时,您会将项目添加到该列表中。

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

【讨论】:

  • 我忘了添加我创建 Form1 的新实例并在表单加载时使用它访问汽车列表我试图添加我的类 form2 的构造函数但没有成功
  • 抱歉,您有什么要问我的吗?你想达到什么目标,我看看能不能帮到你?
  • 我尝试添加(创建 form1 的实例并使用汽车列表调用它)和平按钮的代码,但它不起作用。你有其他解决方案吗
  • 打开第二个表单的按钮2在哪里?
  • 但是将物品添加到汽车的代码是在按钮单击中。我仍然不确定您要做什么。
【解决方案2】:

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

我建议您创建一个新类来托管相关列表(可能作为单例,或由“主”表单实例化)。这样,您就可以在Form1Form2 之间共享列表。

【讨论】:

  • 我忘了添加我创建 Form1 的新实例并在表单加载时使用它访问汽车列表我试图添加我的类 form2 的构造函数但没有成功
猜你喜欢
  • 2018-10-29
  • 2012-04-07
  • 2010-12-06
  • 2017-04-26
  • 2019-07-13
  • 1970-01-01
相关资源
最近更新 更多