Tuesday, February 5, 2013

SharePoint 2010 - Creating a Classic Webpart

Overview
Classic webparts can be created by deriving from the WebPart class. You must write the code from scratch, in the CreateChildControls method, to create the layout design of the Web Part, which can be time consuming. One of the challenges that you face when designing a Web Part that has a complex user interface (UI) is the lack of drag-and-drop support.

Creating a Classic Webpart
Following are the steps for creating a Classic Webpart.

1) Open Visual Studio and select "New Project->SharePoint->2010". The following window will open displaying all SharePoint project templates. Select "Empty SharePoint Project", give a suitable name and click "Finish".

2) The following window pops-up. Enter the suitable Site collection name for debugging purpose. You also have the option to select Farm Solution or Sandboxed Solution.  

3) Right click on Solution and select Add->New Item. 

4) Another window with SharePoint templates will open as shown in the below figure. Select "Web Part".

 5) When a webpart is added 2 main components are added. First one is the webpart "MyClassicWP" which contains all the files supporting the webpart. Second one is "Features" contains the features for deploying the webpart to the site.
(Note: We will take a closer look into features in the upcoming posts.)

6) Now we will some custom code to display a welcome text along with date and time. Add the following code in the CreateChildControls() method.
SPWeb currentWeb = SPControl.GetContextWeb(HttpContext.Current);
String currentUserName = currentWeb.CurrentUser.LoginName;
this.Controls.Add(new LiteralControl(String.Format(
"<h1>Welcome {0}!</h1>", currentUserName)));
this.Controls.Add(new LiteralControl(String.Format(
"<div>Current DateTime: {0}</div>", DateTime.Now)));

7) Select "Build-> Deploy MyVisualWebPart" to deploy the webpart to the site collection that we entered in the "SharePoint Customization Wizard" in the 2nd step.
(Note: For deploying the wepart solution to another site collection or subsite we must use the STSADM command line tool or SharePoint Management Shell. We will discuss deployment in detail in the upcoming sessions.)

8) Now open the Webpart page in "Edit mode" and click "Add a Web Part". The webpart "MyClassicWP" is now available in the webpart gallery under "Custom" group. Select the webpart and click "Add".

9) Our webpart has been created and displays the Welcome message along with date and time.

This is just small example of creating a Classic Webpart. In the next post we will create a sample visual webpart.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.