【问题标题】:Dynamically loaded user controls disappear after button press c# win forms按下按钮后动态加载的用户控件消失 c# winforms
【发布时间】:2018-04-29 14:15:35
【问题描述】:

我正在尝试将用户控件的实例动态加载到我的主窗体上,它在加载程序时大部分时间都可以工作,但在加载该用户控件的相应按钮被按下两次后就不起作用了。

我正在使用以下代码来创建用户控件的实例

public partial class patientInfo : UserControl
{
    public static patientInfo _instance;
    public static patientInfo Instance
    {
        get
        {
            if (_instance == null)
                _instance = new patientInfo();
            return _instance;
        }
    }
}

以及在 MainForm 上加载实例的代码

 private void pInfo_Click(object sender, EventArgs e)
    {
        //Patient Info
        foreach (Control ctrl in panel3.Controls)
        {
            ctrl.Dispose();
        }
        if (!panel3.Controls.Contains(patientInfo.Instance))
        {
            panel3.Controls.Add(patientInfo.Instance);
            patientInfo.Instance.Dock = DockStyle.Fill;
            patientInfo.Instance.BringToFront();

        }
        else
        {
            patientInfo.Instance.BringToFront();

        }
    }

如果我按下此按钮,用户控件将按预期方式加载,但我再次按下它,用户控件将消失。我使用 Dispose 是因为我想在不同的鼠标按钮上加载和卸载多个用户控件。 请指教谢谢。

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    执行对象的dispose 方法会释放非托管资源,但不会从表单中移除控件。除了在使用完资源后释放它,您还需要使用控件的remove 方法将其从表单中删除。见 S.O.答案:How to programmatically remove Form controls

    另外,请参阅 Microsoft 示例:Control.ControlCollection.Remove Method (Control)。示例代码:

    // Remove the RadioButton control if it exists.
    private void removeButton_Click(object sender, System.EventArgs e)
    {
       if(panel1.Controls.Contains(removeButton))
       {
          panel1.Controls.Remove(removeButton);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多