Trying to pass values to the main Form

Hello,
I am trying to make a second Form to send an integer to the main Form. With a breakpoint, I can check the main Form loads the correct value from the second Form (loaded into test_int), but if I run the program again (F5), with a second break I can see that test_int returns always to 0. How to proceed to remind this value in the main Form ?

CODE IN MAINFORM
public partial class Form1 : Form
{
public int test_int;
...
public void get_int(int value)
{
test_int = value;
}

CODE IN SECOND FORM
private void second_form_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Form1 Form1 = new Form1();
Form1.get_int(5);
}

PS: I can not use "return" from the second form because I would like the second form send the value when closing.
[871 byte] By [efkefk] at [2007-11-19 22:36:29]
«« Lux Value
»» Help
# 1 Re: Trying to pass values to the main Form
You are creating a new instance of Form1 and setting the value in that instance, so in essence you have a third form (which I guess you never show) that gets the value 5.

I think this is the most common question in the C-sharp forum...

Nevertheless, you have two objects (an instance of the main form, and an instance of the second form), who needs to pass some data around.

You can:
1. have object a (main form) ask object b (second form) for the value
2. have object b (second form) tell object a (main form) that value has changed
3. keep the value in object c, which both objects a and b have access to

1 could look like this:

// in Main form:
SecondForm sf=new SecondForm();
sf.ShowDialog();
test_int=sf.IntValue;

// in SecondForm:

public int IntValue
{
get { return 5; }
}

2 could look like this:

// in Main form:
SecondForm sf=new SecondForm(this);
sf.Show();

// in Second Form:

private Form1 mainForm;
public SecondForm(Form1 aForm)
{
mainForm=aForm;
}

private void second_form_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
mainForm.get_int(5);
}


3 will be similar to 2, except that you set the value in a third object, you can then use data binding and have both forms show the same value (if it is changed in one form changes will be immediately reflected in the other form).
klintan at 2007-11-9 11:22:38 >
# 2 Re: Trying to pass values to the main Form
Thank you for your help. My problem was I was not passing the parameter "this" when declaring the new second Form. I was doing this:

// in main form
SecondForm sf = new SecondForm()

// in second form
public SecondForm()

So there was no way to get the reference of the main form.
Thank you again.
efkefk at 2007-11-9 11:23:38 >
# 3 Re: Trying to pass values to the main Form
check out this article

http://www.codeproject.com/useritems/PassValueFromAForm.asp
Carter at 2007-11-9 11:24:47 >