C# – Custom property editor for Web parts in SharePoint

csharepoint-2007web-parts

I have created a custom WebPart that has some configuration properties. The values for these properties are a Site URL and list name. I want to show a drop down list with all site names and lists for the selected sites. How can I get to show a custom editor component for a property in SharePoint? I don't want to get the default text editor.

Best Answer

You will want to create a custom ToolPart. Here is a guide: http://sharepoint-insight.blogspot.com/2008/10/sharepoint-creating-web-part-with.html

Basically in your WebPart code you will need to override the GetToolParts function and return a ToolPart[]

Change your toolpart constructor to accept an SPWeb object (pass it the SPContext.Current.Web object from your Web Part). To get the list of lists, in your toolpart you will need to create a dropdownlist inside your CreateChildControls() method. Using the SPWeb object you got from the Constructor you can use a for each to get all the lists for the current site.

So in your web part do this:

public override ToolPart[] GetToolParts()
{
    ToolPart[] tps = new ToolPart[3];

    WebPartToolPart wptp = new WebPartToolPart();
    CustomPropertyToolPart cptp = new CustomPropertyToolPart();
    tps(0) = cptp;
    tps(1) = wptp;
    tps(2) = new ListSelectionToolPart(SPContext.Current.Web, "List Settings");

    return tps;
}

private string _TargetListGUID;
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(false)]
[WebDisplayName("Target List GUID")]
[WebDescription("GUID of the Target List")]
[SPWebCategoryName("Internal")]
public string TargetListGUID {
  get { return _TargetListGUID; }
  set { _TargetListGUID = value; }
}

Add a class like this:

public class ListSelectionToolPart : WebPartPages.ToolPart
{
  private SPWeb _web;
  protected DropDownList ddlLists;

  public New(SPWeb Web, string ToolTitle)
  {
    _web = System.Web;
    this.Title = ToolTitle;
  }

  protected override void CreateChildControls()
  {
        Literal litLists = new Literal { Text = "<b>List:</b><br />" };
        ddlLists = new DropDownList {
        AutoPostBack = true,
        ID = "ddlLists"
        };
        ddlLists.Style.Add("width", "100%");
        foreach (SPList list in _web.Lists)
        {
         ddlLists.Items.Add(new ListItem(list.Title, list.ID.ToString()));
        }
        this.Controls.Add(litLists);
        this.Controls.Add(ddlLists);
  }

  public override void ApplyChanges()
  {
    (this.ParentToolPane.SelectedWebPart as MyWebPart).TargetListGUID = ddlLists.SelectedValue;
  }

}

The above code assumes the name of your WebPart is MyWebPart and that there is a TargetListGUID property. To add a site selection you can do pretty much the same thing in the toolpart (add another dropdownlist). If you use the SelectionChanged event on it you can use it to populate the lists dropdown.

Related Topic