다음을 통해 공유


To enable "Show Tool Bar" option in Document Web Part through Code

I am going to explain a scenario where I had an OOB Document Web Part in one of my page and from code i had to enable the "Show Tool Bar" for that Web Part.

The scenario can be achieved through reflection. The code is given below.

splist -> The Document Library List

webpartID -> Id of the Document Web Part added to the page 

 private static void SetToolbar(SPList splist, string webpartID) 
{ 
 SPWeb web = splist.ParentWeb; 
 SPLimitedWebPartManager manager = web.GetLimitedWebPartManager("default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); 
 SPLimitedWebPartCollection webPartColl = manager.WebParts; 
 XsltListViewWebPart wp = webPartColl[webpartID] as XsltListViewWebPart; 
 
 if (wp != null) 
 { 
 MethodInfo ensureViewMethod = wp.GetType().GetMethod("EnsureView", BindingFlags.Instance | BindingFlags.NonPublic); 
 object[] ensureViewParams = { }; 
 ensureViewMethod.Invoke(wp, ensureViewParams); 
 FieldInfo viewFieldInfo = wp.GetType().GetField("view", BindingFlags.NonPublic | BindingFlags.Instance); 
 SPView view = viewFieldInfo.GetValue(wp) as SPView; 
 Type[] toolbarMethodParamTypes = { Type.GetType("System.String") }; 
 MethodInfo setToolbarTypeMethod = view.GetType().GetMethod("SetToolbarType", BindingFlags.Instance | BindingFlags.NonPublic, null, toolbarMethodParamTypes, null); 
 object[] setToolbarParam = { "ShowToolbar" }; 
 setToolbarTypeMethod.Invoke(view, setToolbarParam); 
 view.Update(); 
 } 
 }

Comments

  • Anonymous
    November 03, 2013
    It works but unable to edit page. Have u experienced that issue

  • Anonymous
    March 05, 2016
    Brilliant!