如何在表单中的用户控件中动态添加和删除用户控件 [英] how to add dynamically and remove a user control from a user control in a form

查看:37
本文介绍了如何在表单中的用户控件中动态添加和删除用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力在表单中添加动态和删除用户控件.我有一个表单,在我的表单中我有一个面板,它有一个静态控件.

I am struggling in adding a dynamic and removing a user control into the form. I have a form and inside my form I have a panel which it has a static control.

我想要实现的是将用户控件添加到面板中.虽然添加很容易,但我知道有更好的方法可以做到这一点.

What I am trying to achieved is to add the user control into the panel. Though it was easy to add but I know there is a better way out there to do this.

通过单击表单中的按钮将用户控件添加到我的面板.

Adding a user control to my panel by clicking a button in the form.

private void btnadd_Click(object sender, EventArgs e)
{
    UserControl1 usr = new UserControl1

    pnlUI.SuspendLayout();
    pnlUI.Controls.Clear();
    pnlUI.Controls.Add(usr);
    pnlUI.ResumeLayout(false);
}
// This one adds it and clearing the control that was already in the panel of the form.

现在,我将删除添加的用户控件并尝试再次显示面板中已删除或清除的控件.

Now, I get stacked here in removing the user control that was added and trying to display again the control that was in the panel that was been removed or cleared.

在我的用户控件上,后退按钮上有一个后退按钮,我正在尝试处理用户控件.但在那之后,原来的控件不再存在,面板已经空了.

On my user control there is a back button on that back button I am trying to dispose the user control. But after that the original control is no longer there and the panel is empty already.

有什么建议吗?

推荐答案

您可以向表单中添加一个实例变量以跟踪上一个控件.这假设面板中永远只有一个控件.

You could add an instance variable to your form to keep track of the previous control. This assumes that there will only ever be one control in the panel.

在你的课堂上:

private Control _previousPanelContent;

然后在您的方法中:

private void btnadd_Click(object sender, EventArgs e)
{
    UserControl1 usr = new UserControl1();

    pnlUI.SuspendLayout();

    // check if there's already content in the panel, if so, keep a reference.
    if (pnlUI.Controls.Count > 0)
    {
        _previousPanelContent = pnlUI.Controls[0];
        pnlUI.Controls.Clear();
    }

    pnlUI.Controls.Add(usr);

    pnlUI.ResumeLayout(false);
}

然后当你想回去时:

    pnlUI.SuspendLayout();
    pnlUI.Controls.Clear();

    // if the previous content was set, add it back to the panel 
    if (_previousPanelContent != null)
    {
        pnlUI.Controls.Add(_previousPanelContent);
    }

    pnlUI.ResumeLayout(false);

这篇关于如何在表单中的用户控件中动态添加和删除用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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