Thursday, December 27, 2012

Hyperlink to ‘Open Edit Tool Pane’ for SharePoint 2010 VisualWebPart

The following post will show you how to use SharePoint’s built-in JavaScript function 'ShowToolPane2Wrapper' to put the WebPartPage into edit mode and have the web parts properties editable.

All that you need is to add ShowToolPane2Wrapper takes 3 parms.

<a href=\"javascript:ShowToolPane2Wrapper('Edit', this,'" + this.ID + "')\">some text</a>

Note: "ID" is the webpart ID, an VisualWebPart uses a UserControl to hold the WebParts code, so use Parent.ID.

All Code
using System;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace SomeVisualWebPart.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        public string ListName { get; set; }
        private Label openToolPaneMessage;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Controls.Clear();

            if (isWebPartConfigured(this.ListName))
            {
                // Add Controls as normal
            }
            else
            {
                this.Controls.Add(this.openToolPaneMessage);
            }
        }

        protected override void OnInit(EventArgs e)
        {
            this.openToolPaneMessage = new Label();
            this.openToolPaneMessage.Style.Add(HtmlTextWriterStyle.PaddingTop, "5px");
            this.openToolPaneMessage.Text = string.Format(CultureInfo.CurrentCulture, "Web part is not configured. <a href=\"javascript:ShowToolPane2Wrapper('Edit', this,'{0}')\">Open the tool pane</a> to set the web part properties.", this.Parent.ID);

            base.OnInit(e);
        }

        private bool isWebPartConfigured(string listName)
        {
            bool isWebPartConfigured = false;

            if (!string.IsNullOrEmpty(listName))
            {
                SPList tmpList = SPContext.Current.Web.Lists.TryGetList(listName);
                if (tmpList != null)
                {
                    isWebPartConfigured = true;
                }
            }

            return isWebPartConfigured;
        }
    }
}

Note:
In SharePoint 2007 this has a 'MSOTlPn_' prefix, MSOTlPn_ShowToolPane2Wrapper.


Result:


No comments:

Post a Comment