pass object to main form when I close it

主宰稳场 提交于 2020-01-17 08:07:28

问题


I have an object that I create in Form2 (Main form is Form1). When I'm done assigning properties to the object in Form2, I would like to have it available in Form1.

The object is created in Form2

public partial class Form2 : Form
private List<POI> POIs_3D;

public Form2()
{
    InitializeComponent();
    POIs_3D = new List<POI>();
}

Then I assign add some values to the list object and want to have it available in Form1.

I know it may be simple but I can't figure out..

EDIT:

This is the code that opens Form2:

private void btn_3d_Click(object sender, EventArgs e)
{
    Form formulario = new Form2();
    formulario.Show();
}

回答1:


There are many ways to do that

1)Declare the object in Form1. Pass it to Form2 on creation. Have Form2 set the Value.

2)Make a property/variable internal in Form2 and have Form1 read the property. This can be a little complicated if you want the result on the closing of Form2 because you will have to call a method in Form1 from Form2 in order to get the value.

3)Make a Property/Variable internal in Form1 and have Form2 set that value. This requires that Form2 knows the instance of Form1. You can pass that in the Owner property of Form2 when showing. Form2.Show(this)




回答2:


In Form2, change this:

private List<POI> POIs_3D;

to this:

public List<POI> POIs_3D { get; private set; }

and now you'll be able to access it on the instance of Form2 that Form1 has. The private set; indicates that nobody else can actually set the value.




回答3:


Why not overload constructor of Form2 (which I guess is created from Form1 code) to take object created in Form1.

public Form2(Object data)
{
    this.dataObject=data;
    InitializeComponent();
}

//in Form1
new Form2(myDataObject);



回答4:


Create a public property of the List POIs_3D

public partial class Form2 : Form

private List<POI> pOIs_3D;
public List<POI> POIs_3D
{
    get { return pOIs_3D; }
    set { pOIs_3D = value; }
}    

public Form2()
{
    InitializeComponent();
    POIs_3D = new List<POI>();
}

In Visual Studio:

  1. Right-Click on the private field
  2. Select "Refactor"
  3. Click on "Encapsulate field"
  4. Click "OK"
  5. Click "Apply"

Update:

You can access the property like this:

public partial class Form1 : Form
{
   private Form2 form2;  

    public Form1()
    {
        InitializeComponent();  
        form2 = new Form2();
        List<POI> myList =  form2.POIs_3D;   //Access the property of Form2    
    }
}


来源:https://stackoverflow.com/questions/20904933/pass-object-to-main-form-when-i-close-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!