Creating Custom Web Part Properties

The Microsoft SharePoint 2010 Web Part framework enables users to configure a Web Part through Web Part properties. A default user interface (UI) is given for each Web Part property that is exposed to the user in the Edit Tool pane of the Web Part. For example, a property of type String is rendered as a text box, and an Enum is rendered as a drop-down list box.

This default rendering by the framework does not allow for much customization because the user cannot get a handle to the controls that are rendered. For example, it has the following limitations:

  • Control over UI: Numeric and string types are rendered as text boxes, enumeration types are rendered as a drop-down list box, and Boolean types are rendered as check boxes. So, you cannot show an enumeration type as radio buttons instead of a drop-down list box.
  • Events: Events that are raised by the controls cannot be handled; for example, you cannot enable or disable a drop-down list based on selecting a check box.
  • Validation: If user input has to be validated, the framework does not provide a way to easily attach a Microsoft ASP.NET validation control to the input control that is generated. For example, you cannot validate a string input for a valid email address through an ASP.NET RegEx validation control.

You can overcome these limitations by using custom editor parts. With custom editor parts, you can offer users functionality that can be achieved through ASP.NET user controls. A Web Part can implement custom editor parts that can be loaded when the Web Part is in edit mode, expose a custom UI, handle events, and validate inputs. A Web Part can have more than one custom editor part associated with it.

SharePoint 2010 Visual Web Parts contain a set of properties that we can use to control its appearance and behavior during runtime. Sometimes we might need to add our own properties to a Web Part so that we can implement more generalized controls, which can be plugged-in to different pages based on a mode or a category.
 
If I just add a Visual Web Part with the default name “VisualWebPart1” to my SharePoint project, I will get a User Control (called “VisualWebPart1UserControl.ascx”) and a Web Part class (called “VisualWebPart1.cs”) inheriting from the WebPart base class. This VisualWebPart1.cs is used to load the User Control as well as to set personalization settings. So I have to add my custom property to the VisualWebPart1.cs.
 
So the basic steps to add a custom property are;
  1. Add a custom property in “VisualWebPart1.cs” Web Part class
  2. Make above custom property visible to “VisualWebPart1UserControl.ascx” User Control
  3. Access custom property from the User Control

 Code to follow or go here for a more detailed explanation:

http://blog.concurrency.com/sharepoint/create-a-custom-web-part-for-sharepoint-2010/

2 thoughts on “Creating Custom Web Part Properties

Leave a comment