Click here to Skip to main content
15,892,737 members
Articles / Programming Languages / C#
Article

Passing an Object between Two .NET Windows Forms

Rate me:
Please Sign up or sign in to vote.
3.05/5 (15 votes)
26 Jan 20043 min read 72.1K   1.3K   22   3
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.

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.

C#
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.

C#
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:

C#
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.

C#
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


Written By
Web Developer
United States United States
Retired electronics engineer who programs as a hobby.

Comments and Discussions

 
Generalnot good code Pin
Anonymous10-Sep-04 11:08
Anonymous10-Sep-04 11:08 
GeneralAmusing. This reminds me... Pin
Marc Clifton26-Jan-04 22:48
mvaMarc Clifton26-Jan-04 22:48 
GeneralRe: Amusing. This reminds me... Pin
Larry102427-Jan-04 5:00
Larry102427-Jan-04 5:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.