将对象传递给新表单

时间:2016-05-08 16:45:58

标签: c# winforms

我想做那样的事情:

的MainForm:

Car car = new Car(); //create new object
Form form2 = new Form(car); //Create new form and pass the car that I've created a line before.
form2.Show(); //Show the second Form

窗体2:

public Car(Car car)
    {
        InitializeComponent(); //here the car is visible, in private method below, for the button, I can't get to it.
    }

    private void button(object sender, EventArgs e)
    {
        car.maker = "VW" //update the information about the car. I can't make this line to work, variable "car" is unavailable here, how to get to it?
        this.Close(); //close second form
    }

当我在form2中添加有关汽车的所有信息时,如何在form2中找到此对象并将其返回给MainForm?

1 个答案:

答案 0 :(得分:1)

在form2中创建一个属性

public Car MyCar {get; set;}

并设置此属性

Car car = new Car(); //create new object
Form form2 = new Form(); 
form2.MyCar=car;
form2.ShowDialog(); 
// get car here again
 Car car2 =form2.MyCar;