关闭动态创建的Winform

时间:2018-01-01 17:05:43

标签: c# forms winforms

我正在动态创建一个winform并将winform声明为类变量。我有表单启动,并完全按照我的需要显示,但是我的Close()事件并没有按照我的需要关闭表单。

如何修改此语法,以便在按下按钮时关闭动态创建的子表单?

(参见下面代码中注释的编译错误)

//class variable
private Form noempselected; 

private void btnValidateData_Click(object sender, EventArgs e)
{
    string employee = cboEmployeeSelect.Text;
    if (employee == "--Select An Employee--")
    {
        using (noempselected = new Form())
        {
            Label messagelabel = new Label();
            messagelabel.Size = new System.Drawing.Size(378, 22);
            messagelabel.Name = "lblMessageToUser";
            messagelabel.Location = new System.Drawing.Point(1, 9);
            messagelabel.Text = "Please select an Employee!";
            Button closebutton = new Button();
            closebutton.Location = new System.Drawing.Point(126, 43);
            closebutton.Name = "btnCloseForm";
            closebutton.Size = new System.Drawing.Size(101, 42);
            closebutton.TabIndex = 7;
            closebutton.Text = "Close";
            closebutton.UseVisualStyleBackColor = true;
            closebutton.Click += new System.EventHandler(CloseForm_Click);
            noempselected.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            noempselected.ClientSize = new System.Drawing.Size(396, 160);
            noempselected.Controls.Add(messagelabel);
            noempselected.Controls.Add(closebutton);
            noempselected.Name = "noempselected";
            noempselected.Text = "No Employee Selected";
            noempselected.ResumeLayout(false);
            noempselected.PerformLayout();
            noempselected.ShowDialog();
        }
    }

    private void CloseForm_Click(object sender, EventArgs e)
    {            
        //Simply using close does nothing
        //Close();

        //This throws compile error of The type or namespace name 'noempselected' could not be found (are you missing a using directive or an assembly reference?)  
        noempselected nes = new noempselected();
        nes.Close();
    }

1 个答案:

答案 0 :(得分:2)

当简单地调用Close()时,这实际上适用于您的顶级表单,而不是您要关闭的表单。它相当于this.Close(),而不是您正在寻找的内容。它什么都不做的原因是因为你的子表单是模态的,所以this.Close()被忽略了。 (作为测试,尝试在打开子窗体时手动关闭主窗体.Spoiler:什么都不会发生。)

此外,您无法在此处使用发件人,因为发件人是一个按钮。将Button投射到Form将返回null

要让您的代码按原样运行,请使用:

private void CloseForm_Click(object sender, EventArgs e)
{
    noempselected.Close();
}

最后,noempselected是私有字段,而不是类型。出于这个原因,noempselected nes = new noempselected();根本不是你可以做的事情。你有正确的想法,只是错误的语法!