May 14, 2012

Adding Properties to a Web Part

When you create web parts for SharePoint, you can give the content managers the possibility to set some properties for the web part. These properties need to be set in the beginning of the webpart class, e.g.

private int_numTiles;

[WebBrowsable(true), //needed for visibility in web part properties in browser
WebDisplayName("Number of tiles per row"), //set the display name for the property field
WebDescription("Number of tiles per row"), //description for the property
Personalizable(PersonalizationScope.Shared), //enables setting the property for the shared view
Category("Tile Settings") //create your own property group (instead of the default Miscellaneous)
]

public int numTiles
    {
            get { return (_numTiles); }
            set { _numTiles = value; }
    }

The property above would be a simple text box field. You can use different types of properties to collect the settings data needed:
  • string, int and DateTime are text fields
  • enum is a dropbox
  • bool is a checkbox
As for this particular case (that is, setting the number of tiles on a row in my Metro Tile Web Part) where the only possible number range that my web part would accept, the dropdown (enum) would be a better approach than a text box, or at least that way I can bypass the otherwise mandatory if-else (or property value check) by offering only the possible choices. The enum type in itself is a bit more work thatn the other properties, for you need to 
  • declare the enum type first:
    public enum TileEnum{One=1,Two=2,Three=3,Four=4,Five=5};
  •  then declare the property:
    private  TileEnum _numTiles;
    ...
    public  TileEnum  numTiles ...
  • and in this case, convert the value to int for use in switch
    int TilesPerRow = (int) numTiles;
    switch (TilesPerRow){
    Case 1:
         tileclass = "onetile";
         break;
    ...


[The article about creating the tile web part: Creating a Metro Tile Web Part]


No comments: