blah blah blah is here! blah blah » Close

up0down
link

Let's say I have form1 and form2. Form1 and Form2 are open. You click a button on Form2 and it adds 1 to a variable called myNumber on Form1.

Now the problem is I can't use the new keyword and create a new instance of Form1, because Form1 declares myNumber setting it to 0 on creation of the form. If myNumber gets set to 0 again then all the 1's that were added to that variable were added for nothing....

How do I pass a variable from Form2 to Form1 without creating a new instance of Form1?

last answered one year ago

2 answers

up1down
link

You can get a reference to the existing instance of Form1 and increment myNumber as follows:

Form1 f1 = (Form1)Application.OpenForms["Form1"];
f1.myNumber++;

This assumes, of course, that myNumber is declared as either a public or internal instance field of Form1.

Thank you

up0down
link

Have an event in Form2 that requires a Form1 referenced parameter with one of the arguments passed in the event the variable in Form2:

//Form1
Form2 form2;
public Form1()
{
InitializeComponent();
form2.VariableChange += new VariableHandle(form2_event)
}
void form2_event(int variable)
{
//Do something with variable
}

//Form2
public delegate void VariableHandle(int variable);
public event VariableHandle VariableChange;

void UpVariable()
{
varialbe++;
VariableChange(variable);
}


Hope this helps!

Feedback