Export (0) Print
Expand All

TemplateControl.LoadControl Method

Obtains a UserControl object from a user control file.

[Visual Basic]
Public Function LoadControl( _
   ByVal virtualPath As String _
) As Control
[C#]
public Control LoadControl(
 string virtualPath
);
[C++]
public: Control* LoadControl(
 String* virtualPath
);
[JScript]
public function LoadControl(
   virtualPath : String
) : Control;

Parameters

virtualPath
The virtual path to a user control file.

Return Value

Returns the specified UserControl object.

Remarks

If the user control supports caching, the object returned from this method is not actually a UserControl, but a PartialCachingControl.

Example

[Visual Basic, C#] The following example uses the LoadControl method to add a user control, LogOnControl, to an ASP.NET page. LogOnControl is contained in the Logonformcs.ascx file, for C#, or the Logonformvb.ascx file, for Visual Basic. The user control is then added to the Controls property of a PlaceHolder Web server control named myPlaceholder.

[Visual Basic] 
' When this page is loaded, it uses the TemplateControl.LoadControl
' method to programmatically create a user control. The user control
' is contained in the .ascx file that is passed as a parameter 
' in the LoadControl call. The page then adds the control to its
' ControlCollection.
Sub  Page_Load(Sender As Object, e As EventArgs)
         
  ' Obtain a UserControl object MyControl from the
  ' user control file TempControl_Samples1.vb.ascx.
  Dim myControl1 As MyControl = CType(LoadControl("TempControl_Samples1.vb.ascx"),MyControl)
  Controls.Add(myControl1)
              
End Sub

[C#] 
// When this page is loaded, it uses the TemplateControl.LoadControl
// method to programmatically create a user control. The user control
// is contained in the .ascx file that is passed as a parameter 
// in the LoadControl call. The page then adds the control to its
// ControlCollection.
void Page_Load(object sender, System.EventArgs e)
  {
    // Obtain the UserControl object MyControl from the
    // user control file UserControl_Init.ascx.
    MyControl myControl1 = (MyControl)LoadControl("TempControl_Samples1.cs.ascx");
    Controls.Add(myControl1);
    
  }

[C++, JScript] No example is available for C++ or JScript. To view a Visual Basic or C# example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 2000, Windows XP Professional, Windows Server 2003 family

See Also

TemplateControl Class | TemplateControl Members | System.Web.UI Namespace

Show:
© 2014 Microsoft