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

.NET programming topics
Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

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

Post by Neo » Sun Feb 07, 2010 2:24 am

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);
}
User avatar
Herath
Major
Major
Posts: 417
Joined: Thu Aug 05, 2010 7:09 pm

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

Post by Herath » Sun Jul 24, 2011 2:13 pm

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 341 times
Last edited by Neo on Sun Jul 24, 2011 4:06 pm, edited 1 time in total.
Reason: Tabs are placed as indents to syntax
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

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

Post by Neo » Sun Jul 24, 2011 4:23 pm

Cool :)
Post Reply

Return to “.NET Programming”