Sometimes you have to dynamically create controls. For standard elements, everything is simple:
Label testLabel = new Label ()
{
Text = "TEST"
};
Page.Controls.Add (testLabel);
This code will add an element of type Label with the text "TEST".
For user items, things are a little more complicated, but also easy.
First, it’s necessary to add a reference to the page to which the control will be added (instead of register, which is used when we add control during design):
<% @ Reference Control = "~ / ctrls / MyWebCtrl.ascx"%>
Comment: as rightly noted by ostapbender , Reference must be declared when the asp.net site project model is used, if you use the asp.net web application, then such an ad is admissible, but useless because in such a project model, initially all parts work in one namespace and “know” about each other.
Then, to instantiate the class of control in your logic, you need to use LoadControl:
ctrls_MyWebCtrl ctrl = (ctrls_MyWebCtrl) LoadControl ("~ / ctrls / MyWebCtrl.ascx");
Now you can set all the properties of the object or call the necessary methods. The ready control is added to the ControlCollection container on the page; usually, the standard PlaceHolder control is used for this.
PlaceHolder1.Controls.Add (ctrl);
One remark, it is recommended to explicitly specify the class name when creating the control:
<% @ Control ... ClassName = "ctrls_MyWebCtrl"%>
This value will be used in the dynamic creation of the control; if it is not specified, the value will be formed from the name of the control file.
It's all.