Programmatically setting toolbar type for list view web part [SharePoint]

If you ever tried to programmatically set the toolbar type for a list view web part then you will find that this is not at all straightforward. There are actually quite a lot of posts about this on the net, and they all involve using reflection to invoke various private methods. The simplest way I have found is to invoke the SetToolbarType private method of the SPView class. Using ILSpy you can see that there are two overloads for this method, one takes a uint and the other takes a string for the toolbar type. The first overload translates the uint to a string value and invokes the second overload.

For a recent project we used PowerShell to add the list view web part to a rich text field on a page and then turn off the toolbar. Below is the complete script to do this – please review the inline comments.

###Declare a custom enum. The names of the enum members match the string values that the SetToolbarType method expects.
Add-Type -TypeDefinition @"
    public enum ToolbarType
    {
        Standard,
        FreeForm,
        None,
        ShowToolbar
    }   
"@

###These functions are required as we are adding the web part to a rich text field, rather than to a web part zone.
Function RegisterWebPartForPageRendering([Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager] $webPartManager, [System.Web.UI.WebControls.WebParts.WebPart] $webPart)
{
    $WEB_PART_ZONE_ID = "wpz";

    $webPartStorageKey = [Guid]::NewGuid()
    $webPart.ID = GetWebPartIDFromStorageKey $webPartStorageKey

    $webPartManager.AddWebPart($webPart, $WEB_PART_ZONE_ID, 0);
    return GetHtmlForWebPart $webPartStorageKey
}

Function GetWebPartIDFromStorageKey([Guid] $storageKey)
{
    return "g_" + $storageKey.ToString().Replace('-', '_');
}

Function GetHtmlForWebPart([Guid] $webPartStorageKey)
{
    return [String]::Format(@"

<div class='ms-rtestate-read ms-rte-wpbox' contentEditable='false' unselectable='on'>

<div class='ms-rtestate-notify ms-rtestate-read {0}' id='div_{0}' unselectable='on'></div>


<div style='display:none' id='vid_{0}'unselectable='on'></div>

</div>

"@, $webPartStorageKey.ToString());
}

###This is the method that does the magic. It is invoked by the main script below.
Function SetViewToolbar([Microsoft.SharePoint.SPView] $view, [ToolbarType] $toolbarType)
{
    $setToolbarTypeParameterTypes = [uint32]
    $setToolbarTypeMethod = $view.GetType().GetMethod("SetToolbarType", [System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic, $null, $setToolbarTypeParameterTypes, $null)
    $setToolbarParameters = [uint32] 1
    
    $setToolbarTypeMethod.Invoke($view, $setToolbarParameters)
    $view.Update()
}


###Get the web's landing page. The web part will be added to this page.
$web = Get-SPWeb "http://myServer/myWeb"
$publishingWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
$defaultPage = $publishingWeb.DefaultPage

###Check out the page so we can edit it
$defaultPage.CheckOut()

###Get the page's web part manager
$defaultPageItem = $defaultPage.Item
$webPartManager = $defaultPageItem.File.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

###Delete all the web parts currently on the page
$allWebParts = $webPartManager.WebParts | Select $_
ForEach ($webPart in $allWebParts)
{
    $webPartManager.DeleteWebPart($webPart);
}

###Instantiate a new list view web part
$targetList = $web.Lists.TryGetList("My List")
$listViewWebPart = New-Object Microsoft.SharePoint.WebPartPages.XsltListViewWebPart
$listViewWebPart.ListName = $targetList.ID.ToString("B")
$listViewWebPart.ViewGuid = $targetList.Views["My View"].ID.ToString("B")
$listViewWebPart.Title = "My List View Web Part"

###Add the web part to the rich text field
$content = RegisterWebPartForPageRendering $webPartManager $listViewWebPart
$defaultPageItem["PublishingPageContent"] = $content

###As we are adding a new web part to be page, be sure to call Update on the page before 
###accessing the View property of the web part, otherwise it will be null.
$defaultPageItem.Update()

###Access the View used by the list view web part and set the toolbar type
$view = $listViewWebPart.View
SetViewToolbar $view None

###All done, update the page and check in.
$defaultPageItem.Update()
$defaultPage.CheckIn([String]::Empty, [Microsoft.SharePoint.SPCheckinType]::MinorCheckIn)
Advertisement

About Bernado

Based in Australia, I am a freelance SharePoint and Dynamics CRM developer. I love developing innovative solutions that address business and everyday problems. Feel free to contact me if you think I can help you with your SharePoint or CRM implementation.
This entry was posted in SharePoint 2013. Bookmark the permalink.

3 Responses to Programmatically setting toolbar type for list view web part [SharePoint]

  1. Hi Bernado,
    Thank you for the example.
    Cheers

  2. roshanjv says:

    Thank You!!! This really helped

  3. Aleksandrs says:

    Bernardo, thank you very much for sharing!
    For them, who will use this excellent code – it is important to call $defaultPageItem.Update(), otherwise it will not work. You can just caml query the item by LinkFilename and update it.

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 )

Facebook photo

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

Connecting to %s