marți, 24 noiembrie 2009

[C#] [GUI] Dynamically loading a user control

Dynamically loading a user control:
1. Create the control.
2. Add the control to the form’s Controls collection.
3. register any event for that control
4. Set the control’s properties for size/position.
5. Make the control visible (Visible = true).
6. Set the control’s z-order (BringToFront()).

public partial class MyUserControl : UserControl {...};
UserControl m_Ctrl = new MyUserControl();
m_partCtrl.OnClosed += new EventHandler(CloseUserControl);
PanelMain.Controls.Add(part);
m_Ctrl.Dock = DockStyle.Fill;
m_Ctrl.Visible = true;
m_Ctrl.BringToFront();
this.Text = "Focused window - " + m_Ctrl.ToString();


Removing User Controls
private void CloseUserControl(object sender, EventArgs e)
{
MyUserControl _Ctrl= (MyUserControl)sender;
_Ctrl.CloseWinPart -= new EventHandler(CloseUserControl);
_Ctrl.Visible = false;
MainPanel.Controls.Remove(_Ctrl);
_Ctrl.Dispose();
this.Text = "Main Form";
}

!!! - failing to unhook events can cause memory leaks

Niciun comentariu:

Trimiteți un comentariu