+ Reply to Thread
Results 1 to 2 of 2

Thread: Transfer Data Between Forms

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    13

    Transfer Data Between Forms

    I want to transfer data or even control one of the controls of one form from the other.
    Okay say i have 2 different Forms , Form1.cs and Form2.cs and you want to pass a bool or string value from form1 to form2.

    How can that be done ?
    Last edited by lucky; 11-09-2012 at 12:23 AM.

  2. #2
    Junior Member
    Join Date
    Jun 2012
    Posts
    10
    Steps :
    --------
    1) create the two forms
    2) create a publick bool variable
    3) assign it to true from form2

    Okay let`s begin :

    FORM 1 :

    Code:
            public bool istrue = false;
    
            private void button5_Click(object sender, EventArgs e)
            {
                Form2 f2 = new Form2(this);
                f2.Show();
            }
    The inserted this is essential that`s to pass Form1 to Form2.
    And Yeah it will give you an error near "this" but it is okay and you will figure out why in a few moments.

    FORM2 :

    Code:
        public partial class Form2 : Form
        {
            Form1 f1;
            public Form2(Form1 form1)
            {
                InitializeComponent();
                f1 = form1;
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                f1.istrue = true;
            } 
        }
    Now as you can see that you can access any public variable from another Form , and now the error on Form1 is gone , know why ?
    Because we added Form1 form1 , and that means when you call Form2 from Form1 you are expected to pass Form1 with it.

    You can actually manipulate anything on Form1 , just set the modifier to public and you will gain access to it.

    Like for example if we set Button5_Click modifier to Public then when you click button1 on Form2 it will also click button5 on Form1 :
    Code:
            public void button5_Click(object sender, EventArgs e)
            {
                Form2 f2 = new Form2(this);
                f2.Show();
            }
    Code:
            private void button1_Click(object sender, EventArgs e)
            {
                f1.istrue = true;
    
                f1.button5_Click(new object(), new EventArgs());
            }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts