5,443,978 members and growing! (20,107 online)
Email Password   helpLost your password?
Languages » C# » Windows Forms     Intermediate

Passing an Object between Two .NET Windows Forms

By Larry1024

Two Visual Studio designer created forms are displayed. Buttons and TextBoxes on the forms demonstrate how a DateTime object can be passed between the forms. The second form can be thought of as a dialog box and the object passed back could be the encapsulated results of the dialog operation.
C#Windows, .NET, .NET 1.0, .NET 1.1, Win2K, WinXPVS.NET2003, Visual Studio, Dev

Posted: 26 Jan 2004
Updated: 26 Jan 2004
Views: 36,394
Bookmarked: 10 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
14 votes for this Article.
Popularity: 2.73 Rating: 2.38 out of 5
5 votes, 35.7%
1
2 votes, 14.3%
2
2 votes, 14.3%
3
2 votes, 14.3%
4
3 votes, 21.4%
5

Form Object Pass Demo-

A Windows Form as a Dialog Box

This article was prompted by my desire to offer a Windows form in the manner of a File Dialog Box but populated with my own buttons and textboxes. I could display the "dialog" form and make it disappear, no problem. My problem was passing the results of the dialog operation back to the main program and passing configuration information to the dialog box prior to display.

This article presents the solution to my dilemma. Two forms are presented. The first is created by Main(). The second is created then displayed by code in the first form's load event. Think of Form1 as the main program and Form2 as the dialog box. What is passed back and forth is an object of type DateTime. If your data to and from the dialog box can be reduced to an object, this technique should work.

How to effectively Pass information from one Form to another

In each Form's class template, I thoughtfully provided private storage for the object that's to be passed: private DateTime form1_Time, a method of getting the object (From_Form1_object_form1_GetTime()) and a method to store the object (In_Form1_object_form1_Store_Time(DateTime timeType)). Here're those three (one field and two methods) for class Form1. Form2 contains very similar methods and private data.

private DateTime form1_Time;  // internal container to store DateTime object

public DateTime From_Form1_object_form1_GetTime() 
{    // get DateTime object and send it back

    return form1_Time;
}
public void In_Form1_object_form1_Store_Time(DateTime timeType) 
{                        // take the incoming DateTime object

    form1_Time = timeType;// and then store it internally

}

private Form2 form2;  
// variable to hold object of Type Form2 created when Form1 is loaded

Notice above that I have a private field variable that is a Form2 type, form2. I allocate memory thus creating the actual object "form2" when the Form1_Load event occurs. Here's the code:

private void Form1_Load(object sender, System.EventArgs e)
{
    form2 = new Form2();  
    form2.BringToFront();  // if running this demo in debugger, form is 

    form2.Show(); //minimized at first so force form2 to open

}

This is just about all we need. The newly created form2 object has access (scope) to the private object (the form2's DateTime construction) through form2's wordy Get and Store methods described above. If you think of form1 as your main program, we can send information to form2 (dialog box) by calling these methods. For example, your current configuration could be stuffed into an object and sent to the DialogBox (here Form2) for presentation to the user. Here in this demonstration program, I'm just sending the current time in response to a button click on Form1.

private void button1_Click_Form1_SendTime(object sender, System.EventArgs e)
{                 // send time to form2 object

    DateTime buttonClickTime = DateTime.Now;
    // run method located in object form2

    // named "In_Form2_object_form2_Store_Time"

    form2.In_Form2_object_form2_Store_Time(buttonClickTime);
}

Now, consider that the user has completed filling out the dialog box and clicks the "accept" button (in this analogy, Form2's Send Time button). How do you get the object full of information back in the main program. Just invoke Form2's Get method as shown below:

private void button2_Click_Form1_GetTime(object sender, System.EventArgs e)
{
    // run method named "From_Form2_object_form2_GetTime()"

    // located in object form2

    DateTime timeStoredIn_form2 = form2.From_Form2_object_form2_GetTime();
    textBox1.Text = String.Format( "{0:T}",timeStoredIn_form2);
    // format and display


}

A click on the Get Time button on Form1 invokes the object form2 causing execution on the method From_Form2_object_form2_GetTime(). The method completes returning the DateTime object from form2's private memory space. Then the DateTime object is formatted and presented in a textbox on Form1.

So we've successfully passed access back and forth to a private object by invoking public methods!

Finally, notice that when you first start the program, the Get Time button returns 12:00:00 showing that the private object is indeed empty (null).

Getting a Dialog Result from Form2

I didn't discover this until later but using a form as a dialog box is apparently a common technique. In fact, you can get a DialogResult from a button press in the same manner as a MessageBox. Here's a snip from the .NET Doc that shows this idea. A wonderful idea, but useless without knowing how to retrieve information from the DialogBox.

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.

   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.

      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

I have no idea why something so incredibly easy now was so difficult then. I literally spend hours figuring out how to pass data between two .NET Forms. Good thing I'm retired and patient! Back in the old days of K + R C (pre C++ and pre C#), you could just put a fence around a heap of memory and then drive your bits and bytes in, out and around at will. The main program and dialog box both had access to the memory. One wrote and the other received. Incredibly convenient but then along came the virus writers. Anyway, I hope my explanation was informative and helpful.

History

  • Version 1 - released January 2004.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Larry1024


Retired electronics engineer who programs as a hobby.
Occupation: Web Developer
Location: United States United States

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 3 of 3 (Total in Forum: 3) (Refresh)FirstPrevNext
Subject  Author Date 
Generalnot good codesussAnonymous12:08 10 Sep '04  
GeneralAmusing. This reminds me...editorMarc Clifton23:48 26 Jan '04  
GeneralRe: Amusing. This reminds me...memberLarry10246:00 27 Jan '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 26 Jan 2004
Editor: Smitha Vijayan
Copyright 2004 by Larry1024
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project