【发布时间】: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