Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello
the following code is in Form1.
C#
Form2 f2 = new Form2(ref int x);
f2.ShowDialog();

and this in Form2
C#
int[] Gx=new int[2];
public Form2(ref int[] x)
{
    InitializeComponent();
    for(int i=0;i<2;i++)
    Gx[i]=x[i];
}


What I have tried:

C#
private void method2()
{
    //i want to change value of x in this method Gx is known
    //but x is not known 
    //How can i send  x back to Form1 from here,i also want to do the change of x in this method
}
Posted
Updated 23-Sep-23 11:58am
v3

Just to add to what the others have said, this may help: Transferring information between two forms, Part 2: Child to Parent[^]
 
Share this answer
 
Comments
Engineer khalid 24-Sep-23 6:16am    
Great looks good example
Well, a couple of problems. First, you defined a constructor for Form2 that takes a ref to an int array, but when you created the form instance, you pass in an int, x, not an array.

Since you're showing the Form2 instance with ShowDialog, the Form2 code isn't being called by anything in Form1, so no functions can return a value.

You can, however, create and set a property on Form2 that the Form1 code can pickup after the Form2 instance is closed or dismissed.
 
Share this answer
 
There are multiple ways of returning data to the parent from a Form:

1. Add an event to Form2. The parent subscribes to the event and Form 2 raises the event when a value needs to be returned. The parent will need to unsubscribe from the event once Form2 is closed and will be destroyed to avoid memory leaks.

2. Add an Action/Function delegate to Form2. Pass a method from the parent in the constructor, or a property/method before showing the form and Form2 calls the method to pass the value to be return to the Action/Function delegate. Form2 will need to destroy the Action/Function delegate reference when closing to avoid memory leaks.

3. Add a static class to manage sharing of the data
3-1. a property/method is used on the static class that the Parent passes an Action/Function delegate to. Form2 can then call the Action/Function delegate via the property to pass the value back to the parent.
3-2. a property is used on the static class to store a value. Form2 sets the value before closing. The Parent listen to Form2 for the closing event, then reads the value from the static class

And there are many more different ways of passing the value back. It's best to pick a method that bests suits your needs. Option 1. may be the best for your skill level.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900