Web Parts and ASP.NET Custom Controls
Before writing any code you need to understand a bit about the structure of Web Parts. Web Parts are very similar to ASP.NET Custom controls. If you already have experience creating ASP.NET Custom controls, you will find it very easy to create Web Parts.
ASP.NET provides two abstractions for extending the server control framework: user controls
and custom controls
. User controls are essentially ASP.NET pages with an .ascx file extension that you can insert into standard .aspx Web Form pages. When you build user controls in VS .NET you can drag and drop server controls onto the user control design surface. Unfortunately, you can't create Web Parts visually; instead, you must create ASP.NET custom controlswhich don't support VS .NET's graphical design environment. Each custom control class inherits from System.Web.UI.WebControls.WebControl, which itself inherits from the System.Web.UI.Control class. You will generate the HTML for each control by overriding the base class' RenderContents
method. This method provides an HtmlTextWriter object as an input parameter that you can use to generate robust HTML rather than simply concatenating strings.
The difference between a Web Part and a custom control is that instead of creating a class which inherits from WebControl, you create a Web Part class by inheriting from the Microsoft.SharePoint.WebPartPages.WebPart class. The WebPart classlike WebControlinherits from System.Web.UI.Control. The WebPart class handles interactions with WebPartPage and WebPartZone classes to support adding, deleting, customizing, connecting and personalizing Web Parts on a page. You need to override the RenderWebPart
method rather than the RenderContents
method when creating Web Parts.
The Web Parts infrastructure provides additional advantages over other ASP.NET custom controls. User can drag completed Web Parts from Web Part galleries and drop them onto Web Part Zones. User can modify personal or shared properties of your Web Part and make them persistent. The most interesting and important evolution is that Web Parts connect with each other using standard interfaces.
For this example, you'll create a simple Web Part containing a Label control that will display "Hello World" in this section.
/// Render this Web Part to the output
/// parameter specified.
/// <param name="output"> The HTML writer to
/// write out to </param>
protected override void RenderWebPart(HtmlTextWriter output)
//Create a Lable
Label myLabel = new Label();
//Write the Text
myLabel.Text = "Hello World";
//Add the lable control to the page
//Render the Html output
|TIP: Don't forget to add your controls to Controls list before you render the output.
Now build the project. VS. NET creates a MyWebPart1.dll
and a MyWebPart1.pdb
in the bin
directory you specified for the project's output location.