我什么时候开始和处置我的用户控件?我的、控件、什么时候开始、用户

2023-09-04 03:10:43 作者:只许你做我心尖上的人

在一个WinForms应用程序,我有一个选择的形式。窗体有一个控制t检讨和面板控制。 根据用户的选择,在我要加载的树视图/添加一个用户控件的面板控制。 当我应该创建/启动用户控件?在窗体加载事件处理程序,或一旦TreeView节点被选择? 我应该处理的用户控件中的关闭事件处理程序?

In a winforms application I have an options form. The form has a treview control and a panel control. Depending on the users choice in the treeview I want to load/add a usercontrol to the panel control. When should I be creating/initiating the usercontrols? On the form load eventhandler or once a treeview node is selected? And should I be disposing of the usercontrols in the from closing eventhandler?

这是我的code:

public partial class Options : Form
{
    //usercontrols
    Connections _connections;
    Notifications _notifications;
    Proxy _proxy;

    private void Options_Load(object sender, EventArgs e)
    {
        treeViewOptions.ExpandAll();

        _connections = new Connections();
        _notifications = new Notifications();
        _proxy = new Proxy();
    }

    private void treeViewOptions_AfterSelect(object sender, TreeViewEventArgs e)
    {
        switch (treeViewOptions.SelectedNode.Name)
        {

            case "NodeConnection":
                ControlPanel.Controls.Clear();
                ControlPanel.Controls.Add(_connections);
                break;
            case "NodeNotifications":
                ControlPanel.Controls.Clear();
                ControlPanel.Controls.Add(_notifications);
                break;
            case "NodeProxy":
                ControlPanel.Controls.Clear();
                ControlPanel.Controls.Add(_proxy);
                break;
        }
    }
}

感谢

推荐答案

解决方法:

public partial class Options : Form
{
    //usercontrols
    Connections _connections;
    Notifications _notifications;
    Proxy _proxy;

private void Options_Load(object sender, EventArgs e)
{
    treeViewOptions.ExpandAll();

    _connections = new Connections();
    _notifications = new Notifications();
    _proxy = new Proxy();
}

private void treeViewOptions_AfterSelect(object sender, TreeViewEventArgs e)
{
    ControlPanel.Controls.Clear();

    switch (treeViewOptions.SelectedNode.Name)
    {

        case "NodeConnection":

            ControlPanel.Controls.Add(_connections);
            break;
        case "NodeNotifications":

            ControlPanel.Controls.Add(_notifications);
            break;
        case "NodeProxy":

            ControlPanel.Controls.Add(_proxy);
            break;
    }
}

   private void Options_FormClosing(object sender, FormClosingEventArgs e)
    {

        _connections.Dispose();          
        _notifications.Dispose();
        _proxy.Dispose();

    }

}