在winforms应用程序中,我有一个选项表单。该表单具有treview控件和面板控件。 根据树视图中的用户选择,我想加载/添加用户控件到面板控件。 我应该何时创建/启动用户控件?在表单加载事件处理程序或选择树视图节点后? 我应该在关闭事件处理程序中处理用户控件吗?
这是我的代码:
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;
}
}
}
由于
答案 0 :(得分:1)
是的,你需要解决这个问题。现在您正在泄漏用户控件实例,它们不会自动处理。他们的终结者也没有照顾这份工作。一段时间后,当程序消耗了10,000个窗口句柄时,程序将崩溃。
使它看起来与此相似:
private void treeViewOptions_AfterSelect(object sender, TreeViewEventArgs e)
{
foreach (Control ctl in ControlPanel.Controls) ctl.Dispose();
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;
}
}
答案 1 :(得分:1)
<强>解决方案:强>
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();
}
}