Pass Values Between Windows Forms

This question comes up so often that I thought it might be a good idea to put together a code example. "How can I pass a value from one form to another".

There are a number of ways to do this; I will show just two. The first method is to make the control on the first form (in this case a TextBox) public, and pass a reference to the first form into the constructor of the second form:

public partial class Form1 : Form
    {
         public Form1()
        {
             InitializeComponent();
        }

         private void button2_Click(object sender, EventArgs e)
         {
    // TextBox1 needs to be public to do this.
    // pass a reference to this form into the constructor of Form2
            Form2 form2 = new Form2(this);
            form2.Show();
        }

         private void button1_Click(object sender, EventArgs e)
         {
    //Store the value of the TextBox in the AppDomain Cache:
            System.AppDomain.CurrentDomain.SetData("text",textBox1.Text);
            Form2 form2 = new Form2(this);
            form2.Show();
        }
    }

The second method involves the use of the AppDomain Cache. (Yes, there is a cache in the AppDomain, it seems that not too many people are aware of it). You can store any object in the AppDomain Cache, just remember to cast it back to the original type when using the GetData method.

    public partial class Form2 : Form
    {
         private Form1 frm = null;
        public Form2(Form1 form1)
        {
            InitializeComponent();
            frm = form1;
        

        }
         //shows the value from the reference to Form1
        private void button1_Click(object sender, EventArgs e)
         {
             this.label1.Text = frm.textBox1.Text;

         }

        // shows the value from the AppDomain Cache
        private void button2_Click(object sender, EventArgs e)
         {
             this.label1.Text = (string) AppDomain.CurrentDomain.GetData("text");
        }
    }

A third option would be to have one or more public static fields in a separate class. These fields could be updated by any form in your application, as well as being able to be read by any form.

You can also use events. Here is an article that details how:

http://www.eggheadcafe.com/articles/20040429.asp

However, bear in mind that if you just want to pass values from one form to another, the .NET eventing mechanism may not be appropriate since the value (and any events) have already occured and been set in the first form. Subscribing to an event exposed by the first form may not help you since the value of the TextBox has already been set before the second form is even opened.

    And there you have it - pass a control value from one form to another. You can download the demo Visual Studio 2010 solution here.

By Peter Bromberg   Popularity  (4400 Views)