将窗体设置为父级引发异常“无法将顶级控件添加到控件”

本文关键字:控件 级控 添加 异常 设置 窗体 | 更新日期: 2023-09-27 18:35:27

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

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

它编译良好,没有任何错误。 但是,当我运行主窗体并单击"系统"按钮时,它会给我一个异常。 我使用相同的按钮单击在另一个代码(不是我的)中执行类似操作,并且没有遇到错误(仅将主窗体设置为父级)。

我做错了什么? 我的主代码中是否有导致此问题的内容?

将窗体设置为父级引发异常“无法将顶级控件添加到控件”

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

您需要将EP.TopLevel属性设置为 false。它将允许您为其设置父级。

进一步阅读。

如果您只想访问另一种形式的变量和控件,那么也许您可以通过其他方式访问它,而不是通过父关系。

好的,显然,这样做的方法是打电话

Form_Child.ShowDialog(this)

然后我可以打电话

FromParent_aVariable = ((Form_Parent)this.Owner).aVariable;

或者如果我在命名空间属性中定义变量,那么

FromParent_aVariable = NameSpace.Properties.Settings.Default.aVariable;

有两种方法。

Form_EnterPassword EP = new Form_EnterPassword();
EP.MdiParent = this;       
EP.Show();

试试这种方式,它对我有帮助。 您需要在表单属性中将主体形式设置为 isMdicontainer = true

我最近遇到了类似的情况。我正在尝试类似的事情,但通过控制来自不同类的子表单。

注:您正在尝试将子窗体"TopMost"设置为不允许它的内容。
在本例中为"MdiContainer"。


要实现此目的,请执行以下操作:

•禁用MainForm"isMdiContainer"属性(无论如何,它的使用已经过时了)。

• 将"窗体最顶层"属性设置为 true。

• 您现在应该能够完成您的功能。


**代码示例:**
/* On your Main Form Class */
private void btnSystem_Click(object sender, EventArgs e)
{
    // Instantiate the Form_EnterPassword by passing the MainForm
    Form_EnterPassword EP = new Form_EnterPassword(this);
    EP.Show(); // No longer as modal Form to display in front.
}
/* Under your EnterPassword Form Class */
// Do not create a new Instance of MyMainForm.
// You want to use the same thread as your MainForm
private MyMainForm mainForm;
/* Constructor */
public Form_EnterPassword(MyMainForm form)
{
    mainForm = form;
    this.Owner = mainForm; // "this" refers to the: EnterPassword Form.
}


言论:您(可能)必须做的唯一额外事情(以达到完美)是检查 MainForm> WindowState;并创建一个代码块,以最小化表单或使表单进入其特定状态。

即:

if (WindowState == FormWindowState.Minimized)
{ /* Code to Minimize all the Child Forms. */ }
else { /* Code to bring all Forms to their "Normal" State */ }

以这种方式编写,使对话框显示在父窗体的中心。

   Form_Child.StartPosition = FormStartPosition.CenterParent;
   Form_Child.ShowDialog(this);