Share via


Creating a Web Part with Custom Properties

This programming task describes how to create a Web Part with custom properties. The Web Part base class contains a set of properties that you and the users of your Web Part can use to control its appearance and behavior. For example, a Web Part's Height and Width properties can be set by your code, the user, or the Web Part definition file (.dwp) you use to import a Web Part. A custom property is a property that you create when you need additional properties to enhance your Web Part's functionality.

By default, the custom properties you create and specify as able to be browsed are displayed automatically in the default property pane, making their use transparent to the user. If the default property pane isn't rich enough in functionality, you can create a custom user interface called a tool part to manipulate your custom properties. For information on creating a tool part, see the Creating a Web Part with a Custom Tool Part programming task.

To start this programming task  

  • Perform the steps described in Creating a Basic Web Part, up to the steps for "Defining the logic and rendering of your Web Part."

Creating custom properties

If you used the Web Part templates provided on MSDN, a default custom property is already created for you. But if you used the default Web Control Library templates, then there is one high-level step that you must complete to add a custom property to your Web Part: You must change your XML settings.

Change your XML settings

You can create a custom property in essentially the same way you create a property for a standard ASP.NET Web Form control, but with a few additional requirements.

Because Web Part properties can be customized and are saved in the SharePoint storage system as XML, you must do the following to support the properties you want saved:

  • Add a reference to the System.Xml.dll assembly to your project.
  • Include the XML Serialization namespace by adding the following using directive near the top of the code:
    using System.Xml.Serialization;
  • Add an XML namespace attribute, either at the root level of your assembly or at the property level. If you add the XML namespace at the root level, you are not required to assign XML namespaces at the property level. An XML namespace assigned at the property level will override the XML namespace assigned at the root level. The XmlRoot attribute has the following form:
    [XmlRoot(Namespace="name of namespace")]

You can create a new custom property in essentially the same way as you create a property for a standard ASP.NET Web Form control:

  • Create the property accessors.
  • Set Web Part property attributes.

Create the property accessors

Each custom property for your Web Part requires the appropriate get and set accessor methods. In C#, a typical property for a Web Part takes this form:

   [AttributeDeclaration1, AttributeDeclaration2,...]
   public PropertyTypePropertyVariable
   private PropertyTypePrivatePropertyVariable
   {
      get
      {
         return PrivatePropertyVariable;
      }
      set
      {
         PrivatePropertyVariable = value;
      }
   }

The attributes you declare for your custom property determine how it is stored and displayed to users when they personalize your Web Part.

Set Web Part property attributes

You set attributes to customize the behavior of your Web Part in the property pane and to determine how your property will be stored. Most of these attributes are members of the System.ComponentModel namespace which provides classes that are used to implement the run-time and design-time behavior of Microsoft .NET components and controls. There are some attributes, like the WebPartStorage attribute, that are specific to Web Part properties. The following table lists these attributes and describes how they affect the behavior of your property.

Attribute Purpose
Browsable Set to false if you don't want to display the custom property in the property pane. Also, if you set the WebPartStorage attribute to Storage.None, your property won't display in the property pane.
Category The title of the section of the property pane that you want created to display the custom property. If you don't specify the Category attribute or if you specify the Category attribute as "Default", your custom property is displayed in the Miscellaneous section of the property pane.

Note  If you specify one of the default categories, such as Appearance, your Category attribute setting is ignored, and your property is displayed in the Miscellaneous section.

DefaultValue The default value of the custom property. Specifying the default value minimizes the Web Part's storage requirements by storing the property's value only if it is different from the default.
Description The contents of the tool tip that appears when you pause the mouse pointer over the custom property in the property pane.
FriendlyNameAttribute The caption displayed for the custom property in the property pane. If you don't specify this attribute, the actual property name will be displayed in the property pane.
HtmlDesignerAttribute Used to associate a property builder with the property.
ReadOnly Set to true if you want the custom property to be read-only in the property pane.
ResourcesAttribute Used to provide localized names for FriendlyName, Category, and Description in the tool pane for the custom property.
WebPartStorage Set to Storage.Shared to display the custom property in the property pane when the user is in shared view of the page. Set to Storage.Personal to display the custom property in the property pane when the user is in Shared or Personal view of the page. Set to Storage.None if you don't want the setting to persist for the custom property. The custom property won't be displayed in the property pane.

A Sample Web Part that contains a custom property

The following example illustrates how to implement custom properties of the following types: string, bool, int, float, enum, System.DateTime, and System.Drawing.KnownColor.

To complete this programming task  

  • Cut and paste the following code sample into the C# file for your Web Part project, and then build your project.
//--------------------------------------------------------------------
// File : WebPartCustomProperties.cs
//
// Purpose : A sample Web Part that implements custom properties
//       of the following types: string, bool, int, float, enum,
//       System.DateTime, and System.Drawing.KnownColor
//
//           After building and installing this Web Part, display
//           the property pane to see how the user interface
//           for setting their values is rendered.
//---------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

namespace WebPartLibrary2
{
    /// <summary>
    /// Summary description for CustomPropertyWebPart.
    /// </summary>
    [DefaultProperty("Text"),
        ToolboxData("<{0}:CustomPropertyWebPart runat=server></{0}:CustomPropertyWebPart>"),
        XmlRoot(Namespace="WebPartLibrary2")]
    public class CustomPropertyWebPart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        const string c_MyStringDefault = "Sample String";
        const bool c_MyBoolDefault = false;
        const int c_MyIntDefault = 20;
        const float c_MyFloatDefault = 33.33f;
        public enum myFarmEnum
        {
            barn=0,
            tractor,
            hay,
            pitchfork
        };
        protected myFarmEnum _myEnum;

        // Private variables
        private string _myString;
        private bool _myBool;
        private int _myInt;
        private float _myFloat;
        private System.DateTime _myDateTime;
        private System.Drawing.KnownColor _myColor =
            System.Drawing.KnownColor.Red;

        // Constructor
        public  CustomPropertyWebPart()
        {
            // Initialize private variables.
            _myString = c_MyStringDefault;
            _myBool = c_MyBoolDefault;
            _myInt = c_MyIntDefault;
            _myFloat = c_MyFloatDefault;
            _myEnum = myFarmEnum.hay;
            _myDateTime = System.DateTime.Now;
        }

        // Creates a custom property that is a string.
        // This property will be displayed as a text box in the
        // property pane.

        // Create a custom category in the property sheet.
        [Category("Custom Properties")]
        // Assign the default value.
        [DefaultValue(c_MyStringDefault)]
        // Property is available in both Personalization
        // and Customization mode.
        [WebPartStorage(Storage.Personal)]
        // The caption that appears in the property sheet.
        [FriendlyNameAttribute("Custom String")]
        // The tool tip that appears when pausing the mouse pointer over
        // the friendly name in the property pane.
        [Description("Type a string value.")]
        // Display the property in the property pane.
        [Browsable(true)]
        [XmlElement(ElementName="MyString")]
        // The accessor for this property.
        public string MyString
        {
            get
            {
                return _myString;
            }
            set
            {
                _myString = value;
            }
        }

        // Creates a custom property that is a Boolean value.
        // This property will display as a check box in the
        // property pane.

        [Category("Custom Properties")]
        [DefaultValue(c_MyBoolDefault)]
        [WebPartStorage(Storage.Personal)]
        [FriendlyNameAttribute("Custom Boolean")]
        [Description("Select to set value to True.")]
        [Browsable(true)]
        [XmlElement(ElementName="MyBoolean")]
        // The accessor for this property.
        public bool MyBool
        {
            get
            {
                return _myBool;
            }
            set
            {
                _myBool = value;
            }
        }

        // Creates a custom property that is an integer.
        // This property will display as a text box in the
        // property pane.
        [Category("Custom Properties")]
        [DefaultValue(c_MyIntDefault)]
        [WebPartStorage(Storage.Personal)]
        [FriendlyNameAttribute("Custom Integer")]
        [Description("Type an integer value.") ]
        [Browsable(true)]
        [XmlElement(ElementName="MyInt")]
        public int MyInt
        {
            get
            {
                return _myInt;
            }
            set
            {
                _myInt = value;
            }
        }

        // Creates a custom property that is a float.
        // This property will display as a text box in the
        // property pane.
        [Category("Custom Properties")]
        [DefaultValue(c_MyFloatDefault)]
        [WebPartStorage(Storage.Personal)]
        [FriendlyNameAttribute("Custom Float")]
        [Description("Type a floating point value.") ]
        [Browsable(true)]
        [XmlElement(ElementName="MyFloat")]
        public float MyFloat
        {
            get
            {
                return _myFloat;
            }
            set
            {
                _myFloat = value;
            }
        }

        // Creates a custom property that is a System.DateTime.
        // This property will display as a text box in the
        // property pane.
        [Category("Custom Properties")]
        [WebPartStorage(Storage.Personal)]
        [FriendlyNameAttribute("Custom Date Time")]
        [Description("Type a DateTime value.")]
        [Browsable(true)]
        [XmlElement(typeof(System.DateTime))]
        public System.DateTime MyDateTime
        {
            get
            {
                return _myDateTime;
            }
            set
            {
                _myDateTime = value;
            }
        }

        public bool ShouldSerializeMyDateTime()
        {
            return true;
        }

        // Creates a custom property that is an enum.
        // This property will be displayed as a drop-down list in the
        // property pane.
        [Category("Custom Properties")]
        [DefaultValue(myFarmEnum.hay)]
        [WebPartStorage(Storage.Personal)]
        [FriendlyName("Custom Enum")]
        [Description("Select a value from the dropdown list.")]
        [Browsable(true)]
        public myFarmEnum MyEnum
        {
            get
            {
                return _myEnum;
            }
            set
            {
                _myEnum = value;
            }
        }

        // Creates a property that is a known system color.
        // This property will be displayed as a drop-down list in the
        // property pane.
        [Category("Custom Properties")]
        [WebPartStorage(Storage.Personal)]
        [FriendlyNameAttribute("Custom Color")]
        [Description("Select a color from the dropdown list.")]
        [Browsable(true)]
        [XmlElement(typeof(System.Drawing.KnownColor))]
        public System.Drawing.KnownColor MyColor
        {
            get
            {
                return _myColor;
            }
            set
            {
                _myColor = value;
            }
        }

        public bool ShouldSerializeMyColor()
        {
            return true;
        }
        /// <summary>
        /// Gets the custom tool parts for this Web Part by
        /// overriding the GetToolParts method of the WebPart
        /// base class. You must implement custom tool parts in a
        /// separate class that derives from the
        /// Microsoft.SharePoint.WebPartPages.ToolPart.
        /// </summary>
        /// <returns>
        /// An array of references to ToolPart objects.
        /// </returns>
        // public override ToolPart[] GetToolParts()
        // {
        //  ToolPart[] toolparts = new ToolPart[2];
        //  WebPartToolPart wptp = new WebPartToolPart();
        //  CustomPropertyToolPart custom = new CustomPropertyToolPart();
        //  toolparts[0] = custom;
        //  toolparts[1] = wptp;
        //  return toolparts;
        // }
        /// <summary>
        /// Render this Web Part to the output parameter specified.
        /// </summary>
        /// <param name="output">
        /// The HTML writer to write out to
        /// </param>
        protected override void RenderWebPart(HtmlTextWriter output)
        {
            // Write stored property values to the Web Part.
            output.Write("<b>Stored Property Values</b>");
            output.Write("<br><b>String: </b>" +
                this.MyString);
            output.Write("<br><b>Boolean: </b>" +
                this.MyBool.ToString());
            output.Write("<br><b>Int: </b>" +
                this.MyInt.ToString());
            output.Write("<br><b>Float: </b>" +
                this.MyFloat.ToString());
            output.Write("<br><b>DateTime: </b>" +
                this.MyDateTime.ToString());
            output.Write("<br><b>Enum: </b>" +
                this.MyEnum.ToString());
            output.Write("<br><b>Color Enum: </b>" +
                this.MyColor.ToString());

        }
    }
}

To deploy this sample Web Part  

  • Perform the steps described in the "Deploying your Web Part" section in the Creating a Basic Web Part programming task, making sure to create a SafeControl block and Web Part definition file (.dwp) that reflects the appropriate values for your Web Part assembly.

Displaying custom properties in the property Pane

After you've imported your sample Web Part into a Web Part Page, you can display the property pane to view or change their values. A custom property will be displayed automatically in the default property pane if the property is of type string, bool, int or enum. The following table describes how each of these property types is displayed in the property pane.

Property Type Displayed in property pane as
bool Check box
DateTime Text box
enum Dropdown
int Text box
string Text box

To display or change the values of custom properties  

  • On the Web Part menu, click Modify This Web Part.
  • Expand the Custom Properties section of the property pane.