Export (0) Print
Expand All
0 out of 1 rated this helpful - Rate this topic

TemplateControl.LoadControl Method (String)

Loads a Control object from a file based on a specified virtual path.

Namespace:  System.Web.UI
Assembly:  System.Web (in System.Web.dll)
public Control LoadControl(
	string virtualPath
)

Parameters

virtualPath
Type: System.String

The virtual path to a control file.

Return Value

Type: System.Web.UI.Control
Returns the specified Control.
ExceptionCondition
ArgumentNullException

The virtual path is null or empty.

If the control supports caching, the object returned from the LoadControl method is not actually a Control object; rather, it is a PartialCachingControl object. If the virtualPath parameter is relative, the path of the loaded control is relative to the path of the TemplateControl.

When you load a control into a container control, the container raises all of the added control's events until it has caught up to the current event. However, the added control does not catch up with postback data processing. For an added control to participate in postback data processing, including validation, the control must be added in the Init event rather than in the Load event.

The following code example demonstrates how to use the LoadControl method to add a user control to an ASP.NET page.

In the OnInit event method, this page uses the LoadControl method to programmatically create a user control on the page. The method adds the control to the Controls property of a PlaceHolder Web server control named Placeholder1.

For the definition of the MyControl class that is used in this code example, see TemplateControl.

void Page_Init(object sender, System.EventArgs e)
{
    // Instantiate the UserControl object
    MyControl myControl1 =
        (MyControl)LoadControl("TempControl_Samples1.ascx.cs");
    PlaceHolder1.Controls.Add(myControl1);
}

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.