Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

c# - How do you pass an object from form1 to form2 and back to form1?

I have done some research on this question before deciding to ask it. I just could not find anything that helped me.

I am writing an application in C# for the compact framework 2.0.

I need to take a data object instantiated on form1 and pass that object a form2. Work on the data object in form2 and then pass that data back to form1 so it can be saved.

I understand that a form is just an object an I also understand that objects are past by reference and not by value. I also understand the difference between the two types. I just cannot make it work for some reason.

What is the best, and cleanest, way in code to achieve this?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you need to do is create a second constructor to your second form that accepts an object as a parameter... for all I care, it could be the entire Form1 object instance, then you can get whatever you want from it. Preserve this object in your second form and modify it as needed there. Upon completion of your second form, your first form will have that data and you can do whatever "refreshing" once the second form closes.

public partial class YourSecondForm : Form
{
    object PreserveFromFirstForm;

    public YourSecondForm()
    {
       ... its default Constructor...
    }

    public YourSecondForm( object ParmFromFirstForm ) : this()
    {
       this.PreserveFromFirstForm = ParmFromFirstForm;
    } 

    private void YourSecondFormMethodToManipulate()
    {
       // you would obviously have to type-cast the object as needed
       // but could manipulate whatever you needed for the duration of the second form.
       this.PreserveFromFirstForm.Whatever = "something";
    }


}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...