Pass data from an object created in a secondary form to another formprincipal?

0

I need to run a program in C # that has a MainForm, with a list of customer data and a button to add customer data. In turn if I click on this button, I should open another form where you can enter customer data, click accept and then close the window to return to the MainForm where the list would be updated with the added name.

My problem is that I do the MainForm, I do the other form that opens when I clicked the button, I entered the name and other data, where I create a new client object and I store it but when I close this second window I lose the object and I do not know how to pass it to the MainForm and add it to the list. From the second Form, I do not recognize the list object of the MainForm as to add it there.

    
asked by Sebastián Otero 02.06.2018 в 19:32
source

1 answer

0

There are many ways to do this, but the first thing you need to do is make one instance callable from the other. or access global variables in the program.cs

A simple and good practice method is that your main form is a public global object in your program cs, in this way you can access it from anywhere with program.MainForm

but as in c # the main form is an anonymous object, then it can not be directly referenced, to fix this we have to modify the program.cs class

 public form Mainform 

 Mainform = new form(); 
 Application.Run(Mainform);

Another less invasive method is to use the parent property to access the properties of the form invoked from the main form or the form that invokes it:

inside the mainform in the declaration of the new form

 form formasecundaria = new form();
 formasecundaria.Parent = (this);

within the secondary form;

this.Parent.propiedad = this.propiedad; 

The best practice is to determine how volatile and how many parts these properties should be used.

Global variables / properties are properties that should not be modified every time we want to assign new values.

and having to do the main parent form is always annoying code

I consider that the best practice is that the main form is a global object, in this way you can access all the other properties within your code.

    
answered by 04.06.2018 в 20:26