Cách tạo User Control trong SharePoint 2010

User controls are rapid way to develop custom functionality. There are three steps involved in creating user controls. This article walks through step by step on creating user controls in SharePoint 2010 which displays currently logged in user.

  1. Create and deploy user control
  2. Register user control in the target
  3. Insert the user control wherever required.

Step 1: Create and deploy user control
1. Fire up visual studio 2010, Create a new Empty SharePoint Project.
2. Add an user control to the Project, say “MyUserControl”, Project structure will look like this:


3. Lets build the control now. Go to the code view, Insert a < DIV> and label. Set some CSS styles as like this:

<div id="Main" style="border:1; background-color:#2C84CA; font-size: 25px; color:White;">
    <asp:Label ID="lblUserName" runat="server" Text="0"></asp:Label>


4. The idea is: Lets display the currently logged in user name in the label. Get in to the code behind file (.cs) add this little code.

namespace MyUserControl.ControlTemplates.MyUserControl
    public partial class MyUserControl : UserControl
        protected void Page_Load(object sender, EventArgs e)
            string currentUser = "Current User Name:" + SPContext.Current.Web.CurrentUser.Name;
            lblUserName.Text = currentUser;
SharePoint 2010 user control code behind 

5. Deploying user control in SharePoint 2010: Build and deploy the project. This will create new folder in 14 hive’s Controltemplate’s folder (In my case it was: \14\TEMPLATE\CONTROLTEMPLATES\MyUserControl\MyUserControl.ascx)

Step 2: Register user control in the target

We have our user control ready now. Next step is insert the user control wherever needed. Here, Lets add it to a SharePoint page. say, Default.aspx. By the way, You can load the user control wherever you want, like in Pages, Master pages, Page layouts, and even in Web parts (use Page.LoadControl method)

SharePoint 2010 add user control to page

1. Open SharePoint designer, Open the target site, and then Default.aspx in advanced mode.
2. Register the user control at the top of the page.
<%@ Register TagPrefix=”MyUserControl” TagName=”UserName” Src=”~/_controltemplates/MyUserControl/MyUserControl.ascx” %>

Step 3: Insert the user control wherever required.

We’ve created user control for SharePoint 2010, Registered it on the page. Now, the final step is to include the user control in the page, Here I’ve coded like:
<MyUserControl:UserName id=”MyUserControl1″ runat=”server” />


That’s all! See it in action: SharePoint 2010 user control example. Similar method applies to add user control to SharePoint 2010 master page.

You don’t need to add the user control assemblies in < SafeControl> entry under web.config file explicitly, as all the controls in side CONTROLTEMPLATES folder of 14 hive are trusted by default!