How to add one Form inside another?

Asked

Viewed 3,156 times

1

I have two presses (FormMenuPrincipal and FormFuncionarios) in which when the button btnFuncionarios of Menu is clicked, I want to open the form Employees. I thought I’d add one panel painel as follows:

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

But when running, Visual Studio points out the following error:

An unhandled Exception of type 'System.Argumentexception' occurred in System.Windows.Forms.dll

Additional information: Unable to add level control superior to a control.

The error occurs exactly on the line where I am adding the form inside the panel. What’s wrong ? There is another easier method to do this ?

Remembering that the two Forms cited are "normal" and I don’t want to add exactly in the middle, I want to add it in a certain area.

1 answer

2


This is because, by default, a form is "an independent program", which has "domain of itself" 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 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. I hope it helps.

  • It worked ! You would know how to tell me how to let the form take up all the space (height and width) of the panel ?

  • 1

    I believe it is simple, just set the width and height of the form janela paritr of panel width and height values...

  • 2

    See if this solves Window.. Windowstate = Formwindowstate.Maximized;

  • It worked man, thanks a lot !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.