Saturday, July 18, 2009

Creating a basic sharepoint webpart

In this post I would like to show how to create a basic webpart in sharepoint server 2007 using VS-2005
Step1. create a visual studio class library project and name it as BasicWebpart as shown below

Step2: rename class1.cs in solution explorer to myWebPart.cs

Step3: Add following references microsoft.sharepoint.dll (which will be available at "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI") and system.web.dll by clicking reference tab in solution explorer. Import two dll's in the class file by "using" like below
using Microsoft.SharePoint;
using System.Web;

step4: inherit webpart class of "Microsoft.SharePoint.dll" with class file as shwon below

public class myWebPart : Microsoft.SharePoint.WebPartPages.WebPart

step5: override render method which is inherited from System.Web.UI.Control to put render some sample text. sample method to render the text
protected override void Render(System.Web.UI.HmlTextWriter writer)
{
writer.Write("This is my First basic Web Part");
}

final myWebPart.cs class file code will be as shown below

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Web;
namespace basicWebpart
{

public class myWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
writer.Write("this is my first basic webpart");
}
}

}
step6: compile the project with successful compilation.
step7: Open web.config file of sitecollection where you want to add the webpart which will be located at "OS drive\Inetpub\wwwroot\wss\VirtualDirectories\"
and under SafeControls tag add the below tag to reflect our new webpart in sharepoint site.
<SafeControl Assembly=basicWebpart,Culture=neutral" Namespace="basicWebpart" TypeName="*" Safe="True" />

step8: copy the dll which will be resulted from step 6 to bin directory of the sitecollection.

OS Drive\Inetpub\wwwroot\wss\VirtualDirectories\bin"

with the steps 7 and 8 we completed adding our new webpart to site collection.

to add the new webpart open the desired sitecollection and goto site settings and in site setting page select webpart which will be under gallaries section. and click on new

now select the check box corresponding to your webpart and click populate gallery button.


now goto your desired page where you want to add the webpart and click on edit page and click on ADD WEBPART bar

and add your webart


final webpart is ready on your webpage which will be as shown below.

No comments: