Avoid redundant calling of container events when adding controls at run-time






4.45/5 (3 votes)
Suggestions for adding controls in code
Consider that you have a scenario like this:
- You have a primary (or Main)
Form
in a WinForms Project, 'Form1.' - In this primary Form, you have a
Panel
, 'Panel1,' meant to serve as a container for Controls to be added at run-time (UserControls, WinForms Controls, whatever). - You wish to set the
Dock
property of those to-be-added at run-time Controls in some way so that, as they are added, you take advantage of automatic positioning (and you are willing to sacrifice using theMargin
property, since setting the Dock property will ignore any Margin setting).
// 'InnerPanel here is a UserControl
// 'LeftInnerPanel is a derived UserControl that inherits from 'InnerPanel
//
// 'panel1 here is a Panel created at design-time on the Form with AutoScroll = true.
// the container for all run-time added controls of type InnerPanel, LeftInnerPanel
//
// form scoped variable
private InnerPanel newIP;
// form scoped variable
private int pCount = 0;
// form scoped method, 'Click EventHandler for a Button, 'button1
private void button1_Click(object sender, EventArgs e)
{
// use a variation of the InnerPanel control for left-most UserControl
newIP = (0 == pCount++) ? new LeftInnerPanel() : new InnerPanel();
newIP.Dock = DockStyle.Left;
panel1.Controls.Add(newIP);
}
If you set the 'Dock
property of the control to be added before adding it to its container Control, the 'ReSize
, 'ClientSizeChanged
, and 'SizeChanged
' events of the container Control will not be invoked.
If you set the 'Dock
property after adding the Control to its container Control, those same Events will be invoked twice, as each Control is added.
By this time, I hope you are asking the question: "what's the practical value of this?:"
The way I use it is to watch for the change in the Container control when the number of Controls added suddenly exceed the container Control's boundaries, and Scrollbars are automatically turned on, at which point: in an EventHandler
for one of those Size-changed type Events:
I do some specific stuff related to visual presentation in the UI to simulate how the added Controls would appear if the 'Margin property wasn't 'wiped out' by the fact the Dock
property is set. Very specifically, I adjust the height of the container Panel
so the 'bottoms' of the inserted UserControls
are not 'clipped.'
Other value ?: perhaps just avoiding firing these various size-related Events when you don't need or want to?
Why are the described Events fired twice if you set the Dock
property after adding the Control to its container Control: Ask Microsoft :)