【问题标题】:Closing A Winform That Was Dynamically Created关闭动态创建的 Winform
【发布时间】:2018-01-01 17:05:42
【问题描述】:

我正在动态创建一个 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();
    }

【问题讨论】:

  • 为什么你用 noempselected 初始化 nes = new noempselected();它是形式
  • @programtreasures - 我试图查看实例化表单的新实例是否允许 close() 事件正确触发
  • 既然所有东西都是硬编码的,为什么还要用代码创建呢?
  • @Plutonix - 我不关注

标签: c# forms winforms


【解决方案1】:

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

另外,这里不能使用 sender,因为 sender 是一个按钮。将 Button 转换为 Form 将返回 null

要让您的代码按原样工作,请使用:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 2021-07-15
    相关资源
    最近更新 更多