Tuesday, March 15, 2011

SharePoint Webpart Custom Properties with Default Value

Most of the sharepiont custom development involves creating custom webparts. There could be scenarios where some of the values like connection string, site url, list/library name are configurable by Admin/End User and changeble depending on the requirement. To achieve this for SharePoint webpart, the values can be configured using webpart properties. Any number of webpart properties can be added to the webpart with one or more categories to differenciate. Property value can be modified/changed by modifying the shared webpart.

Webpart property default value can be set using DefaultValue property, as shown below. Note that to set the default value, the value should be stored in a constant variable, otherwise it doesn't work properly.
//Namespaces required
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;

const string const_listName = "ListName";
private string _listName = const_listName;
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[Category("My Category")]
[WebDisplayName("List Name")]
[WebDescription("Provide list name to get all the items.")]
[DefaultValue(const_listName)]
public string ListName
{
    get
    {
       return _listName;
    }
    set 
    {
       _listName= value; 
    }
}

No comments:

Post a Comment