How to add one Form inside another?

1

I have two forms ( FormMenuPrincipal and FormFuncionarios ) in which when the% button of the Menu is clicked, I want to open the Officers form. I thought about adding a panel btnFuncionarios as follows:

private void btnFuncionarios_Click(object sender, EventArgs e)
{
    FormFuncionario janela = new FormFuncionario();
    janela.Visible = true;
    painel.Controls.Add(janela);
}

However when running, Visual Studio points to the following error:

  An unhandled exception of type 'System.ArgumentException' occurred in   System.Windows.Forms.dll

     

Additional information: Can not add level control   greater than one control.

The error occurs exactly on the line where I am adding the form inside the panel. What's wrong ? Is there another easiest method to do this?

Remembering that the two forms mentioned are "normal" and I do not want to add exactly in the middle, I want to add it in a certain area.

    
asked by anonymous 10.04.2018 / 20:39

1 answer

2

This happens because, by default, a form is an "independent program," which has "self-ownership" in relation to user interaction. When you use it as part of another form, in practice it ceases to be "independent."

You need to flag this in the control. So, before adding to the panel, set janela.TopLevel = false; .

Your code will look something like this:

private void btnFuncionarios_Click(object sender, EventArgs e)
{
    FormFuncionario janela = new FormFuncionario();
    janela.TopLevel = false;
    janela.Visible = true;
    painel.Controls.Add(janela);
}

This should work. Hope it helps.

    
10.04.2018 / 21:06