There is no such thing as "call a control". A control is not a method, function, procedure, subroutine, property or operator.
Also, there are not "dynamic" or "static" ways of adding a control. It's always "dynamic". When you use a designer, it simply writes the code for adding controls in forms.
So, the "secret weapon" is simple: if you don't know how to do something in code, try to do it in designer, just to make a code sample. When it is done, look at the auto-generated code (in Forms, it is placed as a child node of the form node in the Solution Explorer of Visual Studio), and learn how to do it.
For example:
Panel parentPanel = new Panel();
TextBox myTextBox = new TextBox();
Button myButton = new Button();
myButton.Click += (sender, eventArgs) => { DoSomethingOnButtonClick(); };
myButton.Click += delegate(object sender, System.EventArgs eventArgs) { DoSomethingElseOnButtonClick(); };
myButton.Parent = parentPanel;
parentPanel.Controls.Add(myTextBox);
[EDIT]
Now, the order of operation:
You need to insert controls in reverse order relative to the order of TAB navigation. You can also adjust
TabOrder
values.
If the form is already shown on screen, you still can add controls, but apparently, the last operations should be
Controls.Add
, to avoid possible flicker. If the form is not shown at the moment of adding control, this rule is not important, but, for the universal approach and better maintenance, I would advice to add controls in last steps, when layout is added.
The regular way to prevent layout flicker is sandwiching code in
SuspendLayout/ResumeLayout
of the top-level parent control, usually
Form
:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.resumelayout.aspx[
^].
[END EDIT]
Again, if you don't know how something else is done, try it with the designer and see how it is done in auto-generated code. But don't copy coding style, end never use auto-generated names, they violate Microsoft naming conventions (because there is no way to observe them in code generation which does not "know" your semantic), always use semantically sensitive names. For adding event handlers, better use anonymous methods.
—SA