45 out of 82 rated this helpful - Rate this topic

Walkthrough: Creating a Basic Web Part

Windows SharePoint Services 3

This walkthrough provides the steps for creating a basic custom Web Part that can be added to your Web Part Pages. It is a simple Web Part that allows the user to define a custom message to be displayed inside the Web Part. This Web Part will derive from the ASP.NET 2.0 Web Part class, which is the recommended practice for Windows SharePoint Services. Note that this walkthrough describes how to create a Web Part without the Visual Studio Extensions for Windows SharePoint Services.

For more information about ASP.NET Web Parts, see the following ASP.NET documentation: ASP.NET QuickStart Tutorials and ASP.NET Web Parts Controls.

Note Note:

You can also develop your Web Parts by using the Visual Studio Extensions for Windows SharePoint Services. By using these extensions, you can greatly reduce the work involved in creating and deploying your Web Parts. The extensions require development in a server environment, and offer the following benefits:

  • Automatic generation of your solution package

  • Automatic generation of the WebPart XML file

  • Ability to deploy Web Parts directly from inside Visual Studio to your Web site

For guidance on using the extensions or to download extensions for Visual Studio 2005 or Visual Studio 2008, see

Windows SharePoint Services 3.0

Visual Studio 2005

To create a Web Part, you start by creating a class library project that derives from the WebPart base class.

To create an ASP.NET Web Part Assembly

  1. Start Visual Studio 2005

  2. On the File menu, point to New, and then click Project.

  3. In Project Types, under Visual Basic or C#, select Windows.

  4. In the Templates pane, select Class Library.

  5. Type Sample.DisplayMessage as the project name.

After you create the project, a blank class file is displayed. You can change the default class name of Class1 to easily identify your new Web Part. In a class library, only a few namespaces are included. You must add two required namespaces and references to their assemblies. You must also derive the base class from WebPart.

To add namespace references and rebase your Web Part

  1. Rename the default class by selecting Class1 in Solution Explorer, right-click, click Rename, and type DisplayMessageWebPart as the file name.

  2. On the Project menu, click Add Reference.

  3. In the Add Reference dialog on the .NET tab, select System.Web and click OK.

  4. In the references area of the class file, add a reference to System.Web.UI.WebControls.WebParts and rebase your class to inherit from WebPart, as shown in the following code sample.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Web;
    using System.Web.UI.WebControls.WebParts;
    
    namespace Sample.DisplayMessage
    {
        public class DisplayMessageWebPart : WebPart
        {
        }
    }
    
  5. You have now created a basic structure for the Web Part.

After configuring the new class to act as a Web Part, add a customizable property for the Web Part.

The Web Part property determines the text that is rendered inside the Web Part. This is customized on the basis of the individual user.

Note Note:

For more information about customization and personalization, see Web Parts Personalization.

For Web Parts based on the ASP.NET Web Parts Pages base class, the tags that are used for the customizable properties are named differently than Web Parts that are based on the WebPart base class. The following list describes each of those properties:

  • The WebBrowsableAttribute class attribute ensures that your custom property renders in the editing tool pane in Windows SharePoint Services.

  • The WebDescriptionAttribute class attribute displays a tooltip to help guide users when editing your custom property.

  • The WebDisplayNameAttribute class attribute shows a display name for your custom property.

  • The PersonalizableAttribute class attribute determines if changes to your custom property affects all users or on a per-user basis.

To create the Web Part property

  1. In the DisplayMessageWebPart file, copy and paste the following code to create a basic customizable property.

    private string customMessage = “Hello, world!”;
    
    public string DisplayMessage
    {
        get { return customMessage; }
        set { customMessage = value; }
    }
    
  2. Then, add the following tags above the public declaration to allow changes on a per-user basis:

    [WebBrowsable(true),
    WebDescription("Displays a custom message"),
    WebDisplayName("Display Message"),
    Personalizable(PersonalizationScope.User)]
    
  3. Now you have created a customizable Web Part property.

Now you must add functionality to your Web Part. By overriding the Control.Render Method, you can tell the Web Part what operations to perform when the page is visited. In this example, the Web Part will render the user-defined text.

To override the Render method and compile the assembly

  1. In the DisplayMessageWebPart file, copy and paste the following code to override the Render method.

    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        writer.Write(DisplayMessage);
    }
    
    
  2. Compile the solution. Now you have an assembly that contains your DisplayMessageWebPart Web Part.

Within a SharePoint site, you can deploy a Web Part assembly to one of two locations listed below. Note that the recommended practice is to deploy assemblies to the bin directory.

  • bin directory — The bin directory is a folder stored in your Web application root directory. For most installations, this is located in the %SYSTEMDRIVE%\inetpub\wwwroot\wss\VirtualDirectories\<port number>\bin directory, but if you need more information, see How to: Find the Web Application Root.

  • Global Assembly Cache (GAC) — The GAC enables you to share assemblies across numerous applications. The GAC is automatically installed with the .NET framework runtime. Components are typically installed in the %SYSTEMDRIVE%\WINDOWS\Assembly directory.

For more information about choosing the correct deployment location, see Deploying Web Parts in Windows SharePoint Services.

For the following example, place the assembly in the bin directory.

Windows SharePoint Services provides a SafeControls list to prevent users from arbitrarily adding server-side code within ASPX pages. The SafeControls list is a list of approved controls and Web Parts that are specific to the SharePoint site that you have designated as safe for invocation on any ASPX page within your site. This list is contained in the web.config file in your Web application root. The local path contains the physical location of the web.config file.

Note Note:

The web.config file is located in the folder where the virtual directory for the Web site is located. This is normally c:\inetpub\wwwroot\wss\VirtualDirectories\<port number>\, but your administrator may have set up your directory differently and this may not be the location of the file.

You can find the location of your web.config file with the Internet Information Services (IIS) snap-in. The IIS snap-in is an administration tool for IIS that has been integrated with other administrative functions. To launch the IIS snap-in and locate the web.config file:

  1. Click Start, point to Programs, point to Administrative Tools, and click Internet Information Services (IIS) Manager.

  2. Expand the node that is the name of your computer, and expand the Web Sites item in the tree

  3. Locate the Web site that is running your Windows SharePoint Services installation (often it is Default Web Site).

  4. Right-click and select Properties.

  5. Select the Home Directory tab.

To add your Web Part to the SafeControls list

  1. Open the web.config file in the application root.

  2. In the SafeControls section of your web.config file, add a SafeControls entry for your custom assembly in the web.config file as follows.

    <SafeControl Assembly="Sample.DisplayMessage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" Namespace="Sample.DisplayMessage" TypeName="DisplayMessageWebPart" Safe="True" />
    

In order to add your Web Part to a Web Part page, you must add it to the gallery.

To add your Web Part to the Web Part Gallery

  1. Navigate to the page on your SharePoint site where you want the Web Part to be accessible.

  2. In the Web Part page, click Site Actions, and select Site Settings.

  3. On the Site Settings page, click Web Parts under the Galleries heading.

  4. On the toolbar in the Web Part gallery, click New.

  5. In the New Web Parts list, check the box next to Sample.DisplayMessage.DisplayMessageWebPart and click Populate Gallery.

  6. Your Web Part can now be added to any Web Part page.

In this step, you import the Web Part to a page in any SharePoint site and test the custom property you added to the Web Part. The following procedure explains the steps for adding the Web Part to a page and changing the Display Message custom property.

To add and test your Web Part

  1. Navigate to the Web Part page on your SharePoint site where you want to add the Web Part.

  2. In the Web Part page, click Site Actions, and select Edit Page.

  3. In the Web Part zone where you want to add the DisplayMessageWebPart, click Add a Web Part.

  4. On the Add Web Parts dialog, find the Miscellaneous category under All Web Parts and check the box next to DisplayMessageWebPart. Click Add.

  5. To modify the text displayed on the Web Part, choose Modify Shared Web Part from the chrome drop-down list.

  6. In the DisplayMessageWebPart properties pane, expand the Miscellaneous category and change the Display Message value. Click Apply.

  7. Now the Web Part is displaying the user-defined value inside the Web Part.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Web Part doesn't appear in the gallery?
The problem I'm having is that the Web Part isn't appearing in the gallery. I followed the steps exactly and it doesn't appear in the New Web Parts gallery list? Any ideas?
Great Tutorial for new SharePointer's
This took me a while to get through because I needed the right dev env set up. I've been learning SharePoint for a day or two and this was a great way to see from start to finish how to build custom WebParts.


Web Part not appearing in Gallery - solution
Two things must occur for the web part to show up.

1. Assembly must be placed either in Global Assembly or in the /bin file of your wss/virtual directory. The default location is C:\Inetpub\wwwroot\wss\VirtualDirectories\80\bin (I'd recommend making a short cut to this, as you'll be using it often. The created web part assembly can be found under your project file, OR, your can right click on your project name and choose properties, then click on build. Select your 80/bin folder for the build location. It skips a step. a

2. Assembly must be registered as "Safe" in your web.config file. Remember your bin folder? Go up one from there and you'll find your web.config. The minimum reference for this is. 
<SafeControl Assembly="MyAssemblyName" Namespace="MyNameSpace" TypeName="*" Safe="True" />
MyAssemblyName is the name on the actual DLL Name
MyNameSpace is the listed NameSpace on your class file
TypeName="*" means that EVERY webpart under this namespace is okay to use.

Shortcut to building MOST webparts
If you are like me, you are probably migrating a bunch of old content/forms, mini apps etc to a sharepoint environment.
Don't bother rebuilding your single page forms. All you need to do is convert them to a web control. 
VS 2005/8 
1. File, add, new - WebControl = this adds your basic structure, use code behind, its okay.
2. Go to old form, copy everything from BETWEEN the body tags, paste into new web control
3. do the same with your code, taking care to leave the partial class name alone. Ensure all hyper links are absolute, as the concept behind a web part says it can be dropped anywhere.
4. Save your new webcontrol to "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES" This is the default location for your primary 'hive'
5. Use this code for your new part. Starting from a new web part project


public class SimpleControlWebPart: System.Web.UI.WebControls.WebParts.WebPart
{
protected UserControl SimpleControl = null;
protected override void CreateChildControls()
{
this.SimpleControl = (UserControl)Page.LoadControl("/_controltemplates/SimpleControl.ascx");
this.Controls.Add(this.SimpleControl);
}
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
this.EnsureChildControls();
this.SimpleControl.RenderControl(writer);
}
}

This assumes that SimpleControl is the name of your .ascs (web control) file. and that it has been saved to the control templates folder.
Deploy your web part.dll to your bin folder.
register as a safe control in web.config
go to your web part gallery and click new and look for your NAMESPACE.WEBPART, click it and hit populate gallery
edit any page, and drop your web part there. This is by far the easiest way to get rapid web parts up on sharepoint. Develop with normal .net features, and simply convert over to a web control and cruise on.

Gl, hf
To add your Web Part to the Web Part Gallery


Navigate to the page on your SharePoint site where you want the Web Part to be accessible.

In the Web Part page, click Site Actions, and select Site Settings.

On the Site Settings page, click Web Parts under the Galleries heading.

On the toolbar in the Web Part gallery, click New.

In the New Web Parts list, check the box next to Sample.DisplayMessage.DisplayMessageWebPart and click Populate Gallery.

Your Web Part can now be added to any Web Part page.
SOLUTION: Web Part not appearing in Gallery

This is for those of you having problems getting this to appear in your Web Parts gallery. There is an error in the example. This assumes that you followed the directions above exactly:


In Step 2, where you created a basic structure for your web part, you would have named your class DisplayMessage.


Then, in Step 6, you were told to add the following code to the web.config file:

<SafeControl Assembly="Sample.DisplayMessage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" Namespace="Sample.DisplayMessage" TypeName="DisplayMessageWebPart" Safe="True" />



The error is that the Class name in your code has to match the TypeName in the web.config file. Change one of them to match the other, recompile your project, save your web.config file, and your Web Part should then appear in the list.

Error: Atrribute specifier is not a complete statement

I have a question regarding the block of code: (step 3.2)

< WebBrowsable(True), _
WebDescription("Displays a custom message"), _
WebDisplayName("Display Message"), _
Personalizable(PersonalizationScope.User) > _

Somehow it keeps giving me an error; "Atrribute specifier is not a complete statement, Use a line continuation to apply the attribute to the folling statement"

Can anyone tell me how you resolved this? I have tried unifying the whole block (removing the _'s) with no luck.
I am using VWD Express... Can that be the problem? Thank you!!

Andez:
Fine for me. Make sure there is no space between the final underscore _ and your property declaration as follows. With the continuation line character you cannot have spaces:

Imports System.Web.UI.WebControls.WebParts

Public

Class DisplayMessageWebPart Inherits WebPart Private _customMessage AsString = "Hello mary doll"

<WebBrowsable(

True), _

WebDescription(

"Displays a custom message"), _

WebDisplayName(

"Display Message"), _

Personalizable(PersonalizationScope.User)> _

PublicProperty DisplayMessage() AsStringGetReturn _customMessage EndGetSet(ByVal value AsString)

_customMessage = value

EndSetEndPropertyProtectedOverridesSub Render(ByVal writer As System.Web.UI.HtmlTextWriter)

writer.Write(_customMessage)

EndSub


End

Class
Create Simple Web Part for SharePoint 2007
VisualStudio Add-In for web parts generation
Check this step-by-step tutorial that shows how you can create a template as regular ASCX control and then use a VisualStudio Add-In to generate a web part based on that template: http://www.codeproject.com/KB/sharepoint/webparts_generator_addin.aspx

Add-In and related assemblies are hosted on codeplex: http://www.codeplex.com/aspnetlibrary
Web part never shows in gallery
I added the public key token into the web.config (as i had to sign it to drop it in the gac)... still doesn't work :(
Where the VS2008, .NET 3.5, VB walkthrough for creating a web part?
Same problem as other people web part never appears in gallery. Have tried procedure twice all the way through with an exceptional eye for detail. So whats the issue ? Ive wasted 2 hours and i only did this because it seemed like its simple enough to work.. guess not
Web Part not in gallery
I'm having the same problem as everyone else...the custom web part doesn't appear in the Web Part Gallery. I've followed this example exactly.
Cannot see the webpart in the gallery
WebPart never appears in gallery. Did anybody got through this issue?
Cannot find newdwp.aspx

Hi,

Like mingssn, I can't point my browser to http://server/_layouts/newdsp.aspx - it can't find the page...

I'm running Sharepoint Services... Anyone got any ideas? With other tutorials, I've always added the dll to the GAC, but now I'm trying the 'bin' method... My self made webpart file doesn't work. I get a 'can't import this webpart' error.

Thanks

Note this example is for WSS 3.0

To Ernest Alias: I suspect you are running Sharepoint 2003, not Sharepoint 2007.

These details will only work for ASP.Net 2.0 and Sharepoint 2007.

To mingssn: The page is present in my WSS 2007.

Namespace property in step 4 is incorrect

There is one error in the above example, most people probably caught it on their own.

In the coding example, the assembly name chosen was "MyWebPartLibrary" that contains a
like-named namespace and a single class of "HelloWorldWebPart".

In Step 4 when updating the web.config, it shows the Assembly property being set
with the classname of "HelloWorldWebPart" when it should be the assembly name
of "MyWebPartLibrary"

How to install an assembly into the Global Assembly Cache in Visual C#
assembly name is correct

Hi dwlovell,

the first steps says to create the project with the "HelloWorldWebPart" name which means that is the project name.

hence the below script posted in the above doc is correct:

<SafeControl Assembly="HelloWorldWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" Namespace="MyWebPartLibrary" TypeName="*" Safe="True" AllowRemoteDesigner="True"/>

Thanks

Personalizable property
The example works well and would be great if an optional configurable property be exposed. 
the example doesn't work
When I tried to deploy this example, I got an error which said that I can only add web parts which are inherited from Microsoft.SharePoint.WebPartPages.WebPart.
few more question...

My site does not display properly if I add AllowRemoteDesigner="true", after remove this attribute, my site works fine...not sure why

Also, I am using Sharepoint service, I can not find newdwp.aspx, is this file/function comes only with portal server?

AllowRemoteDesigner
I think it indicate whether the web part allow design by remote tool such as Office SharePoint Designer.
AllowRemoteDesigner
What does the AllowRemoteDesigner attribute do in the web.config file? Why is it set to True? thanks.