Set form as Parent throw exception "Top-level control cannot be added to a control"

CaTx picture CaTx · May 25, 2012 · Viewed 25.3k times · Source

I want to access variables of a form from another form. On clicking a button inside my Main form, I want to set my Main form as Parent, then bring up another form (child form) wherein I will access variables of the Main form. My click handler is as follow:

private void btnSystem_Click(object sender, EventArgs e)
{
    Form_EnterPassword EP = new Form_EnterPassword();
    EP.Parent = this;        //error: Top-level control cannot be added to a control
    EP.ShowDialog();
}

It compiles fine without any error. However, when I run the Main form and click on the System button, it throws me an exception. I do something similar in another code (not mine) with the same button click, and encounter no error (just with setting Main form as Parent).

What am I doing wrong? Is there something in my Main code that cause this?

Answer

Grzegorz W picture Grzegorz W · May 25, 2012

Best way would be to use EP.ShowDialog(this) and later use Owner property.