Wednesday, March 16, 2011

SharePoint Webpart Load UserControl (UserControl Webpart)

Creating a webpart to load the usercontrol instead of writing the html and business logic within the webpart itself.

Follow the below four steps to create a webpart with usercontrol.
1. Create a Asp.Net UserControl (.ascx file)
The .ascx file should inherit the code behind file as namespace.
<%@ Control Language="C#" AutoEventWireup="true" Inherits="MyProject.MyUserControls.MyClassName, MyProject, Version=, Culture=neutral, PublicKeyToken=681f114f2a212052" %>
2. Create .acsx.cs (code behind) class file as namespace for business logic
using System.Web.UI;
namespace MyProject.MyUserControls
public class MyClassName : UserControl
protected void Page_Load(object sender, EventArgs e)
//Code goes here...
3. Create a webpart

4. Load the UserControl in createchildcontrols() method.
Make sure that the .ascx file is deployed to layouts folder.
PlaceHolder ph;//placeholder to load the usercontrol
protected override void CreateChildControls()
ph = new PlaceHolder();
ph.ID = "profileUpdatePH";

string userControlFilePath = "~/_layouts/MyFolder/MyControl.ascx";
MyUserControls.MyClassName myControl = Page.LoadControl(userControlFilePath) as MyUserControls.MyClassName;


No comments:

Post a Comment