将表单设置为父级抛出异常“无法将顶级控件添加到控件”。 [英] Set form as Parent throw exception "Top-level control cannot be added to a control"

查看:547
本文介绍了将表单设置为父级抛出异常“无法将顶级控件添加到控件”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从另一种形式访问某种形式的变量。在单击主窗体内的按钮时,我想将主窗体设置为父窗体,然后调出另一个窗体(子窗体),在其中我将访问主窗体的变量。我的点击处理程序如下:

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();
}

它编译良好,没有任何错误。但是,当我运行Main窗体并单击System按钮时,它引发了异常。单击相同的按钮,我在另一个代码(不是我的代码)中执行了类似操作,并且没有遇到任何错误(仅将Main form设置为Parent)。

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).

我在做什么错误?

推荐答案

最好的方法是使用 EP。 ShowDialog(this),以后使用 Owner 属性。

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

这篇关于将表单设置为父级抛出异常“无法将顶级控件添加到控件”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆