Page 1 of 1

How to pass controls from one form to another using C#

Posted: Sun Feb 07, 2010 2:24 am
by Neo
There are several methods. The easiest is to write a public property on Form2 to pass the string of the test box as in following example.

Code: Select all

public string MyTestBox {
	get {return textbox1.Text;}
	set {textbox1.Text = value;}
}

Now add the following code to Form1. Then you are able to access the controls of Form2 by using above method.

Code: Select all

Form2 form2;

public Form1()
{
	InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
	form2 = new Form2();
	form2.Show();
}

private void button1_Click(object sender, EventArgs e)
{
	MessageBox.Show(form2.MyTestBox);
}

Re: How to pass controls from one form to another using C#

Posted: Sun Jul 24, 2011 2:13 pm
by Herath
In Form2 I have,

Code: Select all

	private void trackBar1_Scroll(object sender, EventArgs e)
	{
		Form1 f = (Form1)this.Owner;
		f.Controls["textBox1"].Text = trackBar1.Value.ToString();
	}
I am showing the Form2 as a child form of Form1. This also seem to work fine. I was expecting a invalid cross threading error. :). But not getting any due to this child and parent connection (same tread i guess).
cthread.rar
(24.75 KiB) Downloaded 360 times

Re: How to pass controls from one form to another using C#

Posted: Sun Jul 24, 2011 4:23 pm
by Neo
Cool :)