To get the BASICs working, do the following.. Create a new project. Nothing of your current code, windows, etc... The default project will create a form "Form1" leave it alone for now.
Add a NEW form to the project, it will default to "Form2"... Put a single textbox on it and a single button on it. For grins, and clarification to differentiate between the object names, change the name of the controls on Form2 to "txtOnForm2", and "btnOnForm2" (case sensitive for my sample, and readability vs "txtonform2" all lower case). Now, on the form, right-click and click "View Code". It will bring you to the other "Partial class" declaration where your constructors are found. Add the following, dont worry about compile errors as the other half will be when we put code into Form1 next...
// specifically typecasting the TYPE of form being passed in,
// not just a generic form. We need to see the exposed elements
Form1 CalledFrom;
// Ensure to do the : this() to make sure default behavior
// to initialize the controls on the form are created too.
public Form2(Form1 viaParameter) : this()
{
CalledFrom = viaParameter;
}
private void btnOnForm2_Click(object sender, EventArgs e)
{
CalledFrom.ValuesByProperty = this.txtOnForm2.Text;
MessageBox.Show( "Check form 1 textbox" );
string GettingBack = CalledFrom.ValuesByProperty;
MessageBox.Show( GettingBack );
CalledFrom.SetViaMethod( "forced value, not from textbox" );
MessageBox.Show( "Check form 1 textbox" );
GettingBack = CalledFrom.GetViaMethod();
MessageBox.Show( GettingBack );
}
Save and close the Form2 designer and code window.
Now, open Form1. Put a single textbox and a single button on it. The default names for the controls will be "textbox1" and "button1" respectively. Leave it as is. Double click on the button (on form1). It will bring up a snippet for code for that button. Paste the following
private void button1_Click(object sender, EventArgs e)
{
Form2 oFrm = new Form2(this);
oFrm.Show();
}
public string ValuesByProperty
{
get { return this.textBox1.Text; }
set { this.textBox1.Text = value; }
}
public void SetViaMethod(string newValue)
{ this.textBox1.Text = newValue; }
public string GetViaMethod()
{ return this.textBox1.Text; }
Now, save the forms and run them. Click button on first form, calls the second with the already created instance of itself, not a new SECOND instance of itself. The second form will be displayed. Shift the windows so you can see both.
Enter some text in the textbox second window and click the button... follow the back/forth of what is coming/going.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…