How can we use custom controls in SharePoint?

 Posted by ArticlesMaint on 9/24/2009 | Category: SharePoint Interview questions | Views: 5685


Step 1:- Create the custom control by inheriting from the ‘WebControl’ class and override the ‘RenderContents’ method with your implementation. In the below code snippet we are just writing the site title and site URL to the browser.
 

using System.Web.UI;

using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace NameSpaceCustomControl
{
public class CustomControl1 : WebControl
{
protected override void RenderContents(HtmlTextWriter output)
{
SPWeb site = SPContext.Current.Web;
output.Write("The Site title is " + site.Title);
output.Write("<br/>");
output.Write("The URL of the site is " + site.Url);
}
}
}

Step 2:- Compile the custom control class and generate the DLL from the same. Once the compiled DLL is generated, register the same in GAC.

Step 3:- Refer the custom control assembly in your ASPX page using the register attribute. Please note to specify the public key token of the GAC.
 

<%@ Register Assembly="CustomControl,Version=1.0.0.0,Culture=neutral,PublicKeyToken=4adae03f3c0d5b8e" 

Namespace="NameSpaceCustomControl" TagPrefix="CustomSitePages" %>

 


Specify the custom control with a proper unique ID.
 

<CustomSitePages:CustomControl1 ID="cc1" runat="server" />

 


Below is the complete code of the page.
 

<%@ Page Language="C#" MasterPageFile="~masterurl/default.master" meta:progid="SharePoint.WebPartPage.Document"%>


<%@ Register Assembly="CustomControl,Version=1.0.0.0,Culture=neutral,PublicKeyToken=4adae03f3c0d5b8e"
Namespace="NameSpaceCustomControl" TagPrefix="CustomSitePages" %>

<asp:Content runat="server" ContentPlaceHolderID="PlaceHolderMain">

<h3>Hi this is a Site Page</h3>
<CustomSitePages:CustomControl1 ID="cc1" runat="server" />

</asp:Content>


 


Now if you run the page you can see the custom control in action.
 



Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response