A refresher
The ListViewWebPart is used for displaying contents of a List or Document Library on both the default View pages (such as AllItems.aspx, etc) and also on other pages in the same web.
When a List View Web Part is added to a page (say the home page of that web) a hidden view (SPView) is created dedicated to that Web Part. When switching to another view in the Web Part Properties it really copies all the settings of the selected view into the dedicated hidden view. Changes made afterwards to the ‘selected view’ will not be pushed to the ‘dedicated view’.
Today’s question
How to programmatically modify the Toolbar settings for a ListViewWebPart ?
Answer
It all boils down to getting a reference to the hidden dedicated SPView and making modifications to it. There are three options that you can set the Toolbar to:
Full Toolbar
This option translates to “Standard” for the SPView.ToolbarType property.
Summary Toolbar
This option translates to “Freeform” for the SPView.ToolbarType property. Additionally you must specify a CAML string that is used for the rendering of the toolbar.
The default CAML string for a Links List looks like this:
|
]]>Add new link |
|
]]>
No Toolbar
This option translates to “None” for the SPView.ToolbarType property.
The code
I assume you are familiar with getting an instance to the ListViewWebPart and then retrieving the SPView instance using either reflection on the private SPView member or through the public Web and View GUID properties.
Next you can change the Toolbar schema XML through reflection as follows:
SPView view = ...;
Type viewType = view.GetType();
XmlNode toolbarNode = viewType.InvokeMember("GetNodeFromXmlDom", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, view, new object[] { "Toolbar" }) as XmlNode;
toolbarNode.Attributes["Type"].Value = "Standard";
view.Update();