How To Add User Control In A Visual Webpart And In Application Page in Sharepoint

Add User Control, as shown below:

Add a Label and Button to the acsx file, as shown below:

Here is the code of how to add User Control to a Visual WebPart.

  1. private  
  2. const string _ascxPath = @ "~/_CONTROLTEMPLATES/SharePointProject1/UserControl1.ascx";  
  3. public VisualWebPartWithUserControl() {}  
  4. protected override void CreateChildControls() {  
  5.     Control control = this.Page.LoadControl(_ascxPath);  
  6.     Controls.Add(control);  
  7.     Label lblUserControlLabel = (Label) control.FindControl("lblUserControl");  
  8.     lblUserControlLabel.Text = "VisualwebpartControl";  
  9.     base.CreateChildControls();  
  10. }  

This is how Visual WebPart will render. Text VisualwebpartControl shown as text of Label lblUserControlLabel has been changed in CreateChildControls() method of Visual WebPart.

I want to add a point here, that the life cycle of Visual WebPart is completed first; then, the life cycle of User Controls starts.

How to add user control in an application page in SharePoint 2010

Add the below code to an aspx file of an application page.

<%@ Register TagPrefix="UserControl1" TagName="TestControl" Src="~/_CONTROLTEMPLATES/SharePointProject1/UserControl1.ascx" %>

After deploying, this is how the page looks:

Ebook Download
View all
Learn
View all