新文章

2012年12月28日 星期五

[C#]How to operate form1 from form2

There are two forms and form2 were called by form1.























This work is to call Form2 and send text to Form1.
First we need to claim a public variable of Form1 in Form2.
public Form1 f1;

Second,changed the attribute "Modifiers" of textBox1 in Form1 to Public.
Setting textBox1's attribute Modifiers to Public in Form1 can make Form2 to see and operate it.

And the code below:

Form1


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

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.f1 = this;
            f2.Show();
        }
    }
}

Form2


namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        public Form1 f1;
        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            f1.textBox1.Text = textBox1.Text;
        }
    }
}

沒有留言:

張貼留言