c# passing data between forms

2017/10/05 02:07
C# project with two forms

public partial class Form1 : Form // this is the main form

public partial class Form2 : Form // this is the second form
To pass variables (values, data) from Form1 to Form2

Case: public variables in Form2
public string input_variable; // put this in Form2 as global variable

public string output_variable; // put this in Form2 as global variable

in Form1 inside the function that run (call) Form2
Form2 form = new Form2();
form.input_variable= "some string data"; // send the input_variable from Form1 to Form2

DialogResult result = form.ShowDialog();
if (result == DialogResult.OK)
{
    public string local_variable = form.output_variable;
}
In Form2 put an "OK" button that sets the value of output_variable.
private System.Windows.Forms.Button bOK;
this.bOK.DialogResult = System.Windows.Forms.DialogResult.OK;
private void bOK_Click(object sender, EventArgs e)
{
    output_variable = "some string to return to Form1";
}
Case: private variables in Form2

In Form2 create public function that sets all the variables required and takes as parameters the variables transferred from Form1
public void InitData( string str_from_form1)
{
    input_variable = str_from_form1;
}
In Form1 call this function and pass the variable or value required as parameter.
Form2 form = new Form2();
form.InitData(string_to_pass_toForm2);