Thursday, April 10, 2008

How to Pass values to another Form

Ok. Lets say you have 2 Forms. Form1 and Form2.
In Visual Basic 6 this is simple codes with 1 line only: Form2.text1.text = Form1.text1.text

Thats so Simple.

But in C# not 1 line code. I have 2 ways to get a text from Form1/Form2.

FIRST WAY:

1.) Goto Form1 then Double Click it. At the code type this.

public string CaptionText
{get {return textBox1.Text;}
set { textBox1.Text = value; }}


note: the value of your textbox1.text = sayre;

2.) Goto Form2 then Double click it. At the code type this.

// At your command button In Form2
private void button1_Click(object sender, EventArgs e)
{
Form1 sForm1 = new Form1();
textBox1.Text = sForm1.CaptionText;
}


SECOND WAY:

1.) Goto Form2 then Double click it. At the code type this.

public Form2(string sTEXT)
{
InitializeComponent();
textBox1.Text = sTEXT;
}


2.) Goto Form1 then Double click it. At the code type this.
//At your command button in Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 sForm = new Form2(textBox1.Text);
sForm.Show();
}


12 comments:

rachmat said...

in first way, how to view the result??? thanks.

Unknown said...

superb dear thanks.its very useful to me

Tapas Choudhury said...

excellent 2nd way

Unknown said...

I agree, I like the 2nd method more. Really helped me. Thanks! :)

techstuff said...

The Second method is very useful, Thanking you...

hirusoft said...

hey thankz buddy........ 2nd better...

Unknown said...
This comment has been removed by the author.
Unknown said...

Nice One.. thanks

senyum ke langit said...

im using second way and it works!. thanks. but im wonder, why it cannot be view when im using listbox instead of textbox?is there a reason for it?

ramachandran said...

Is it possible to use textbox instead of text box?

balaji said...

Use Sessions...to pass the values from one form to another form...
Session["value"]= texttbox1.text;

Anonymous said...

i appreciate you spending some time and effort to put this article together. i can not wait to read far more from you. this is actually terrific site.

www.triciajoy.com