Friday 30 March 2012

How to Add Custom Webpart Properties in SharePont 2007

Webpart is a nice feature in sharepoint.  Most of the time we need to get some details from the user before the webpart started to work such as the which list you want to proceed.

We can see some default properties are available in the proprety page like appearance and advanced.

The following code explain you how to create a webart with custom property.

 
First off, create a new class that inherits from Microsoft.SharePoint.WebPartPages.ToolPart.
public class SampleToolPart : ToolPart
{
    // First, override the CreateChildControls method. This is where we create the controls.
    protected override void CreateChildControls()
    {
        // create a panel that will hold all of our controls
        Panel toolPartPanel = new Panel();
        toolPartPanel.CssClass = "ms-ToolPartSpacing";
        // create a table that will put our controls in rows
        Table toolPartTable = new Table();
        toolPartPanel.Controls.Add(toolPartTable);
        toolPartTable.CellPadding = 0;
        toolPartTable.CellSpacing = 0;
        toolPartTable.Style["border-collapse"] = "collapse";
        toolPartTable.Attributes.Add("width", "100%");
        // create the first row that will contain a control
        TableRow firstRow = new TableRow();
        toolPartTable.Rows.Add(firstRow);
        TableCell firstRowCell = new TableCell();
        firstRow.Cells.Add(firstRowCell);
        // add formatting to the cells
        firstRowCell.Controls.Add(new LiteralControl("<div class='UserSectionHead'>Sample Dropdown:</div>"));
        firstRowCell.Controls.Add(new LiteralControl("<div class='UserSectionBody'><div class='UserControlGroup'><nobr>"));
        // create the actual control
        DropDownList sampleDropDown1 = new DropDownList();
        sampleDropDown1.ID = "sampleDropDown1";
        sampleDropDown1.Items.Add("Item 1");
        sampleDropDown1.Items.Add("Item 2");
        sampleDropDown1.Items.Add("Item 3");
        // add the new control to the table
        firstRowCell.Controls.Add(sampleDropDown1);
        // add formatting closing tags to the cell
        firstRowCell.Controls.Add(new LiteralControl("</nobr></div></div>"));
        // create a standard dotted line seperator
        TableRow seperatorRow = new TableRow();
        toolPartTable.Rows.Add(seperatorRow);
        TableCell seperatorCell = new TableCell();
        firstRow.Cells.Add(seperatorCell);
        seperatorCell.Controls.Add(new LiteralControl("<div style='width:100%' class='UserDottedLine' />"));
        // lather, rinse, repeat for all the controls you need
        // finally add the panel to the controls collection of the tool part
        Controls.Add(toolPartPanel);
        base.CreateChildControls();
    }
    // Next, override the ApplyChanges method.
    // This method is where we will persist the values that the user selects.
    public override void ApplyChanges()
    {
        // get the parent webpart
        SampleWebPart parentWebPart = (SampleWebPart)this.ParentToolPane.SelectedWebPart;
        // loop thru this control's controls until we find the ones that we need to persist.
        RetrievePropertyValues(this.Controls, parentWebPart);
    }
    // Recursive function that tries to locate the values set in the toolpart
    private void RetrievePropertyValues(ControlCollection controls, SampleWebPart parentWebPart)
    {
        foreach (Control ctl in controls)
        {
            RetrievePropertyValue(ctl, parentWebPart);
            if (ctl.HasControls())
            {
                RetrievePropertyValues(ctl.Controls, parentWebPart);
            }
        }
    }
    // Method for retrieving the values set by the user.
    private void RetrievePropertyValue(Control ctl, SampleWebPart parentWebPart)
    {
        if (ctl is DropDownList)
        {
            if (ctl.ID.Equals("sampleDropDown1"))
            {
                DropDownList drp = (DropDownList)ctl;
                if (drp.SelectedItem.Value != "")
                {
                    parentWebPart.Property1 = drp.SelectedItem.Value;
                }
            }
        }
    }
}

Now, we need to wire up the tool part to the web part. To do this, we override the GetToolParts() method and place our new tool part in the ToolPart array.
 
public class SampleWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
    public SampleWebPart()
    {
        this.ExportMode = WebPartExportMode.All;
    }
    // property that will be set thru our custom tool part
    // make sure to set the WebBrowsable attribute to false
    // so it will not show up outside of our custom tool part
    [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(false)]
    [System.ComponentModel.Category("My Group")]
    [WebDisplayName("Property1")]
    public string Property1
    {
        get
        {
            return _property1;
        }
        set
        {
            _property1 = value;
        }
    }
    private string _property1 = "Default Value";
    public override ToolPart[] GetToolParts()
    {
        // resize the tool part array
        ToolPart[] toolparts = new ToolPart[3];
        // instantiate the standard SharePopint tool part
        WebPartToolPart wptp = new WebPartToolPart();
        // instantiate the custom property toolpart if needed.
        // this object is what renders our regular properties.
        CustomPropertyToolPart custom = new CustomPropertyToolPart();
        // instantiate and add our tool part to the array.
        // tool parts will render in the order they are added to this array.
        toolparts[0] = new SampleToolPart();
        toolparts[1] = custom;
        toolparts[2] = wptp;
        return toolparts;
    }
}

Happy Coding :)