In the development of the ASP.net page, we certainly use the custom UserControl part of the page element, we have two ways to use UserControl
1, Add the required UserControl to the page at design time (most often from solutionexplorer to the design page)
If UserControl is placed in Runat=server HTML tags , it may cause element event handling within the UserControl to not execute correctly.
For example: we sometimes use a div as a border to contain the required UserControl, and for the purpose of controlling the display of the Div at run time (such as hiding/displaying the div at run time), the Div may be set to Runat=server. The element event triggers that are often contained within the UserControl of the Div may be ignored, and the event handlers within the UserControl are often not functioning properly.
2, dynamically load the UserControl using the LoadControl function at run time, and add to the specified location
In the case of dynamic loading, in addition to the same problems as the above, there will be a corresponding initialization problems, then, To ensure that your UserControl works properly with the semantics you want, you must pay attention to two points:
1 If you need to invoke one of UserControl's initialization functions while LoadControl the UserControl. The invocation of the initialization function must be done after the Ctladd to the controls of an element of the specified page, which must be in the following order:
...
MyCtl ctl = (myctl) LoadControl ("path");
This.someCtl.Controls.Add (CTL);
ctl. Initmethod ()//This statement must be followed by the previous article, otherwise the data in the TextBox, ListBox, etc. that need to be persisted will be lost after the event in the CTL causes postback, causing various errors
2 If you need to invoke an initialization function of UserControl at the same time that you loadcontrol the UserControl, be aware that the code that does not need to be executed every time is placed in the IF (! IsPostBack) {} statement block, otherwise it will be run repeatedly at each commit, which is the same as the processing method in Page_Load, but is often easily overlooked.
For dynamically loaded UserControl also make sure to reload all UserControl each time postback (but postback can not initialize the elements in UserControl), otherwise the event handler can not find the corresponding trigger source , data stored in ViewState will not be maintained because the corresponding element is not found.