Communication between forms

1

Hello. I'm working on an application that should work as follows: When it is executed, a main form (Form1) should always open and stay in the background. This main form contains options for the user to make their choices through a button with the text "add". When the user clicks the "add" button it should open another form (Form2) where the user should put their information in textbox and then click a button with the text "save". When you click the "save" button, Form2 should close. The main form should always remain open at the bottom. The user will have other options in the main form that he can choose to fill in other forms (Form3, Form4 ... Formn) and whenever you click on "save" in the forms they will be closed leaving only Form1.

In Form1 you will have a "generate report" button which, when clicked, should export all data saved in other forms to an Excel worksheet.

I have already built the application with all Forms and code to generate the report.

The question is: How do I send the data from other forms to Form1 and are they closed or will they be closed when the user clicks "save"?

I have tried several alternatives of communication between forms but without success. I checked all the options only work if I do a .show () command and open the main form again ... but in my application this can not be done ...

How do I save the data without having to open forms again ... ??

    
asked by anonymous 14.06.2016 / 15:54

1 answer

0

When you open another form, pass form1 as a parameter so that you can access a method inside it so you can save the information returned from the other form.

EXAMPLE FORM 1:

private void Button1_Click(object sender, EventArgs e)
{
    Form2 form2 = new Form2(this); //passe como parâmetro este form1.
}

public void SalvarDadosForm2(string dado1, string dado2, string dado3)
{
    //Salve os dados em variáveis ou outra forma que desejar, 
    //Pode criar um método único ou um para cada form, você quem sabe o melhor jeito.
}

EXAMPLE OF MORE FORMS

In the constructor of the other forms apply:

public partial class Form2: Form
{
    Form1 form1;

    public Form2(Form1 form1)
    {
        InitializeComponent();

        this.form1 = form1;
    }
    // Outras linhas de código, não interessantes ao exemplo.
}

Then do everything you need to do and in the method where the data validation of the other forms ends, include:

   form1.Show();

   form1.SalvarDadosForm2(textbox1.Text, textbox2.Text, textbox3.Text); //Envia as informações para o form1

   form1.Focus();

   this.Close();
    
14.06.2016 / 19:01