0
I’m having a hard time solving this problem.
I created a project in Windows Form to open the other forms inside a panel, being that I would like to associate the Forms to be opened in the variavies at the beginning of the code, maybe I have to refer to this Forms several times during the code, I would like to declare them only once in a variable to use the variable instead of the Forms in the Click of the Buttons but I could not.
Form Formulario1;// Gostaria de colocar o Form a ser aberto aqui e utilizar aenas a variavel
Form Formulario2;// Gostaria de colocar o Form a ser aberto aqui e utilizar aenas a variavel
Form Formulario3;// Gostaria de colocar o Form a ser aberto aqui e utilizar aenas a variavel
Form Formulario4;// Gostaria de colocar o Form a ser aberto aqui e utilizar aenas a variavel
private void Abrir_Formulario<MiForm>() where MiForm : Form, new()
{
Form formulario;
formulario = panel_Formularios.Controls.OfType<MiForm>().FirstOrDefault();
if (formulario == null)
{
formulario = new MiForm();
formulario.SuspendLayout();
formulario.TopLevel = false;
formulario.FormBorderStyle = FormBorderStyle.None;
formulario.Dock = DockStyle.Fill;
panel_Formularios.Controls.Add(formulario);
panel_Formularios.Tag = formulario;
formulario.Show();
formulario.BringToFront();
formulario.FormClosed += new FormClosedEventHandler(Fechar_Formulario);
formulario.ResumeLayout();
}
else
{
formulario.BringToFront();
}
}
// BOTÃO FORMULARIO 1
private void button1_Click(object sender, EventArgs e)
{
Abrir_Formulario<Form1>();// Ideal esse Form vir da variavel no inicio
}
// BOTÃO FORMULARIO 2
private void button2_Click(object sender, EventArgs e)
{
Abrir_Formulario<Form2>(); // Ideal esse Form vir da variavel no inicio
}
// BOTÃO FORMULARIO 3
private void button3_Click(object sender, EventArgs e)
{
Abrir_Formulario<Form3>();// Ideal esse Form vir da variavel no inicio
}
// BOTÃO FORMULARIO 4
private void button4_Click(object sender, EventArgs e)
{
Abrir_Formulario<Form4>();// Ideal esse Form vir da variavel no inicio
}

in the variable
Application.OpenFormsyou have the collection of Forms that is open in the application, just access them... no need to keep saving each one... if you still want to make a parallel list, use aList<Form>https://docs.microsoft.com/pt-br/dotnet/api/system.windows.forms.application.openforms?view=netcore-3.1– Rovann Linhalis
What should you consider: Will the form be reused? If so, do not call Close(), use Hide(). If you call Hide() the form will retain the state (fields, properties, etc.), you can create a Resetfields() (or similar) method to clear the form. Perhaps it is more convenient to create a new form instead of resetting its state, see what suits you best.
– user178974