I'm making a Windows Application in C#.
How to navigate from one form to another and not losing data(s) from the previous form?


For an example,
I created Form1.
In Form1, there's textBox1 and button1.
By clicking button1 links you to Form2,
and after Form2 is shown,
text from textBox1 in Form1 will be printed on label1 in Form2.


If anyone have any idea how to write the codes for the following request, please kindly reply. Help will be appreciated. Thank you. :)

if you use form1 to call form two, you can do something like this inside form1:

Form2 frmSec = new Form2();
frmSec.label1.Text = textbox1.Text;

This method requires that the label1 modifier on Form2 be set to public.

Or, you can do it like this, some might feel this is a more correct way.

//This is the Form2 constructor, which we have modified
public Form2 (string labText)
{
    InitializeComponent(); //it is important that you put this before the next line of code, else an exception is thrown.
    this.label1 = labText;
}

//Now you put this where you call Form2 inside Form1
Form2 frmSec = new Form2(textbox1.Text);

What if I was to link Form1 and Form2 together without losing data(s) but when Form2 was already exist? What codes are to type in Form1 and Form2 to get them in connection?

Example:
By clicking button1 in Form1 will transfer you from Form1 to Form2 and along with the text in textBox1 in Form1 to be displayed in Label1 in Form2.

Please write the codes for both Form1 and Form2 along with the description and explanation.
Thank you.

If an Form2 already exists, then it may be wise to have a member variable in Form1 that refers to the instance of Form2. So when you press the button in the Form1, you can use that variable to manipulate the label in the Form2 instance. Consider:

//FORM1 CODE:
//assuming that the Form2 instance inside Form1 is named frmSec

//insert into button event handler:
frmSec.ChangeLabel(this.textbox1.Text);

//FORM2 code:
public void ChangeLabel(string newText) //make sure this modifier is public
{
    label1.Text = newText;
}

How the frmSec variable gets initialized inside Form1 depends on when Form1 and Form2 are created. It shouldn't be hard for you to figure in that part.

This article has been dead for over six months. Start a new discussion instead.