SharePoint Dragons

Nikander & Margriet on SharePoint

An editor part for a visual web part

This is a follow up to blog post https://sharepointdragons.com/2012/04/06/a-web-part-editor-part-containing-a-drop-down-list/ . Here, we’ll create the same thing, but this time for a visual web part. The differences are minor, but still…

First, we’ve created a user control containing a simple label, just so we’ll be able to show something:

<%@ Assembly Name=”$SharePoint.Project.AssemblyFullName$” %>
<%@ Assembly Name=”Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>
<%@ Register Tagprefix=”SharePoint” Namespace=”Microsoft.SharePoint.WebControls” Assembly=”Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>
<%@ Register Tagprefix=”Utilities” Namespace=”Microsoft.SharePoint.Utilities” Assembly=”Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>
<%@ Register Tagprefix=”asp” Namespace=”System.Web.UI” Assembly=”System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ %>
<%@ Import Namespace=”Microsoft.SharePoint” %>
<%@ Register Tagprefix=”WebPartPages” Namespace=”Microsoft.SharePoint.WebPartPages” Assembly=”Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>
<%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”VisualWebPart1UserControl.ascx.cs” Inherits=”VisualWebPartProject1.VisualWebPart1.VisualWebPart1UserControl” %>
<asp:Label ID=”Label1″ runat=”server” Text=”Label”></asp:Label>

The code behind for this user control contains a public string property. All the control does is display the value of this property in the label:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace VisualWebPartProject1.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        public string MyLabelText { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = MyLabelText;
        }
    }
}

The editor part remains exactly as it was:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;

namespace VisualWebPartProject1.VisualWebPart1
{
    public class WebPart1EditorPart : EditorPart
    {
        // Reference to the web part that uses this editor part, the parent web part needs to implement the IWebEditable interface to support custom editing controls
        protected VisualWebPart1 ParentWebPart { get; set; }
        protected DropDownList EditorChoices { get; set; }

        /// <summary>
        /// Does editor part init settings
        /// </summary>
        public WebPart1EditorPart()
        {
            Title = “Make a choice – good name here”;
        }

        /// <summary>
        /// Creates the dll
        /// </summary>
        protected override void CreateChildControls()
        {
            EditorChoices = new DropDownList();
            EditorChoices.Items.Add(new ListItem(“AAA”, “1”));
            EditorChoices.Items.Add(new ListItem(“BBB”, “2”));
            EditorChoices.Items.Add(new ListItem(“CCC”, “3”));
            Controls.Add(EditorChoices);

            base.CreateChildControls();
            ChildControlsCreated = true;
        }

        /// <summary>
        /// Reads current value from parent web part and show that in the ddl
        /// </summary>
        public override void SyncChanges()
        {
            EnsureChildControls();
            ParentWebPart = WebPartToEdit as VisualWebPart1;

            if (ParentWebPart != null && WebPartManager.Personalization.Scope == PersonalizationScope.Shared)
            {
                ListItem item = EditorChoices.Items.FindByValue(ParentWebPart.MyEditorPartChoice);
                if (item != null) item.Selected = true;
            }
        }

        /// <summary>
        /// Applies change in editor part ddl to the parent web part
        /// </summary>
        /// <returns></returns>
        public override bool ApplyChanges()
        {
            try
            {
                EnsureChildControls();
                ParentWebPart = WebPartToEdit as VisualWebPart1;

                if (ParentWebPart != null && WebPartManager.Personalization.Scope == PersonalizationScope.Shared)
                {
                    ParentWebPart.MyEditorPartChoice = EditorChoices.SelectedValue;
                }

                // The operation was succesful
                return true;
            }
            catch
            {
                // Because an error has occurred, the SyncChanges() method won’t be invoked.
                return false;
            }
        }
    }
}

The web part (ours is called VisualWebPart1.cs) that is responsible for loading the user control is a little different from what it was. Now, it has to cast the user control to our specific type and set our custom string property to the value that was retrieved from our editor part:

Control control = Page.LoadControl(_ascxPath);

var myVisualControl = control as VisualWebPart1UserControl;
if (MyEditorPartChoice == null)
myVisualControl.MyLabelText = “Make a choice first”;
else
myVisualControl.MyLabelText = “The value from the editor part choice: ” + MyEditorPartChoice;

Controls.Add(control);

The complete code for VisualWebPart1.cs looks like this:

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;

namespace VisualWebPartProject1.VisualWebPart1
{
    [ToolboxItemAttribute(false)]
    public class VisualWebPart1 : WebPart, IWebEditable
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @”~/_CONTROLTEMPLATES/VisualWebPartProject1/VisualWebPart1/VisualWebPart1UserControl.ascx”;

        protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);

            var myVisualControl = control as VisualWebPart1UserControl;
            if (MyEditorPartChoice == null)
                myVisualControl.MyLabelText = “Make a choice first”;
            else
                myVisualControl.MyLabelText = “The value from the editor part choice: ” + MyEditorPartChoice;

            Controls.Add(control);
        }

        /// <summary>
        /// Contains the value of the choice in the editor part drop down list
        ///
        /// Set the Personalizable attribute to true,
        /// to allow for personalization of tabs by users.
        /// This causes  this property to be shown in the web part tool pane and lets SharePoint take care of the storage/retrieval of this property in the SharePoint content database.
        /// </summary>
        [Personalizable(true)]
        public string MyEditorPartChoice { get; set; }

        /// <summary>
        /// Creates custom editor parts here and assigns a unique id to each part
        /// </summary>
        /// <returns>All custom editor parts used by this web part</returns>
        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            var editors = new List<EditorPart>();
            var editorPart = new WebPart1EditorPart();
            editorPart.ID = ID + “_editorPart”;
            editors.Add(editorPart);

            return new EditorPartCollection(editors);
        }

        /// <summary>
        /// Returns parent web part to editor part
        /// </summary>
        object IWebEditable.WebBrowsableObject
        {
            get { return this; }
        }

    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: