locked
Update ListViewWebPart to Remove or Hide Toolbar ToolbarType="None"

    Question

  •  

    Anyone know how to change the ListViewWebPart in code programatically to remove the toolbar?

     

    I have tried something lke this:

     

     

    SPLimitedWebPartManager lMgr =

    oSPWeb.GetLimitedWebPartManager(Page_Aspx,  PersonalizationScope.Shared);

    ListViewWebPart wp = (ListViewWebPart)lMgr.WebParts[1];

    lvpart.Title = "test";

    lvpart.ListViewXml = lvpart.ListViewXml.Replace("Standard", "None");

    System.Diagnostics.Debug.Print(lvpart.ListViewXml);

     //// Shows Toolbar Type = None

     

    // update

    lMgr.SaveChanges(lvpart);

     

    // Refresh Mgr

    lMgr = oSPWeb.GetLimitedWebPartManager(Page_Aspx, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

    wp = (ListViewWebPart)lMgr.WebParts[1];

     

    System.Diagnostics.Debug.Print(lvpart.ListViewXml);

     

    /// Shows Shows Toolbar Type = Standard

    // But the Title gets updated!

     

     

    Is this the wrong path or is there an alternate method for doing this? 

     

    Its wierd. 

    Is the Toolbar setting associated with the SPView  or  With the actual web part?

     

     

    Thanks!!

     

     

    Wednesday, August 01, 2007 11:18 AM

Answers

  • The only way to set the toolbar properties that I could find is updating the content database directly.  I was hoping this kind of solution would not be needed in the MOSS 2007 but oh well.

     

    Wednesday, August 29, 2007 4:03 PM
  •  

    Cool....

     Very Close but

    Node is a property of SPView so you need a GetProperty instead of GetField

     

    SPView view = companyLogosLib.Views["Name of View"];

    System.Reflection.PropertyInfo Props = view.GetType().GetProperty("Node", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

    XmlNode node = Props GetValue(view) as XmlNode;

    node.SelectSingleNode("Toolbar").Attributes[0].Value = "None";

    view.Update();

     

    This updates the view on the list (which you cannot even do from the UI !!!) .   However if you apply the this view to the ListViewWebPart    lvpart.ViewGuid = view.ID.ToString("P"

    you still have the tool bar on the listview on your webpart page although the base view does not.  This is because the WebPart's view is a copy of the base view's schema and not the actual view.  But  Eugen Lechner has led the way for us and here is the code to update ToolBar of the ListViewWebPart on a web page.

     

    lMgr =OpenWebPartManager("Default.Aspx");

    // Get web Part

    wp = lMgr.WebParts[wp.ID] as WebPart;

    ListViewWebPart lv = (ListViewWebPart)wp;

    // Extract view

    System.Reflection.PropertyInfo ViewProp = lv.GetType().GetProperty("View", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

    SPView spView = ViewProp.GetValue(lv, null) as SPView;

    // This forces a refresh of the views internal xml or the node's cild nodes are not populated

    string txt = spView.SchemaXml;

     

    System.Reflection.PropertyInfo NodeProp = spView.GetType().GetProperty("Node", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

    XmlNode node = NodeProp.GetValue(spView, null) as XmlNode;

    XmlNode tBarNode = node.SelectSingleNode("Toolbar");

    if (tBarNode != null)

    {

    tBarNode.Attributes["Type"].Value = "None";

    spView.Update();

    }

     

     

    As fun as all this Reflection and XML processing is we are still left with a hack like my direct database update from above that updates private properties that may or may not exists later.  Although better it is still unsupported by MS and could break with the next service pack.  What we need is something high tech like

     

    wp = lMgr.WebParts[wp.ID] as WebPart;

    ListViewWebPart lv = (ListViewWebPart)wp;

    lv.View.ToolBarType = "None";

     

    Come on MS.... Throw us a bone here....

     

    Regards

    Bruce VB

    zNetSys

     

     

     

     

    Tuesday, September 18, 2007 3:58 PM

All replies

  • Maybe something like this?

    List.Views["Name of View"].Toolbar = "None";

    List.Views["Name of View"].Update();

     

    Friday, August 03, 2007 3:32 PM
  •  

    That of course will not work because Toolbar needs to be an HTML string. 

    Thanks for the "Guess", I guess

    Sunday, August 05, 2007 11:26 AM
  • The only way to set the toolbar properties that I could find is updating the content database directly.  I was hoping this kind of solution would not be needed in the MOSS 2007 but oh well.

     

    Wednesday, August 29, 2007 4:03 PM
  • Guess again .. I have done this from code.

     

    My code was used below to update a ListViewWebPart.

     

    NOTE - this code was used in SharePoint Products and Technologies 2003 . but the principals should be the same.

     

     

    Code Snippet

    SPWeb web = SPContext.Current.web;

     

    // Modify title/frametype of the default.aspx web part

    SPWebPartCollection webParts = web.GetWebPartCollection("default.aspx", Microsoft.SharePoint.WebPartPages.Storage.Shared);

     

    foreach (Microsoft.SharePoint.WebPartPages.WebPart webPart in webParts)

    {

    if (webPart is Microsoft.SharePoint.WebPartPages.ListViewWebPart)

    {

    // make some changes to Web Part properties

    webPart.Title = "My Custom Web Part Title";

    webPart.Description = "A custom description too ...";

    // remove the title bar

    webPart.FrameType = Microsoft.SharePoint.WebPartPages.FrameType.TitleBarOnly;

    webPart.DetailLink = "default.aspx";

    // save the Web Part Changes

    webParts.SaveChanges(webPart.StorageKey);

     

    // Remove the Toolbar!

    // this needs to be done from the VIEW of the Web Part

    Guid webPartGuid = new Guid(((Microsoft.SharePoint.WebPartPages.ListViewWebPart)webPart).ViewGuid);

    SPView webPartView = web.Lists["MyListName"].Views[webPartGuid];

    webPartView.Toolbar = "";

    webPartView.Update();

    }

    }

     

     

    Wednesday, August 29, 2007 4:15 PM
  • Alternatively, if the code I provided doesn't work in MOSS, try setting the "Toolbar" property to a blank string ("") instead of "none".

     

     

    Wednesday, August 29, 2007 4:25 PM
  • This approach doesn't work for me in MOSS. I've tried it on document libraries, links, and custom lists. Interestingly, SPView.Toolbar is an empty string before I ever change it, and the documentation (er...what there is of it) says that it should contain CAML.

     

    I thought perhaps I should be changing SPView.ToolbarType instead. The documentation says:

    • Standard —The most common type of toolbar, which is used, for example, in the All Items views for most lists, and which corresponds to Full Toolbar in the Web Part tool pane.

    • FreeForm —Used in Default.aspx and Web Part Pages and corresponds to Summary Toolbar in the Web Part tool pane.

    • None —No toolbar is used in the view, corresponding to No Toolbar in the Web Part tool pane.

    This looks exactly like what I want, but *sigh* ToolbarType is read-only.

     

    I hope the original poster will mark this thread as Not Answered so this discussion will continue. I would dearly love to change the toolbar type programmatically.

     

    fwiw, here is my code...

     

    Code Snippet

    // Can't use "foreach" because it gives a "Collection was modified" error

    // on the second iteration.

    for( int ListNum=0; ListNum<SubSite.Lists.Count; ListNum++ )

    {

    SPList myList = SubSite.Lists[ListNum];

    // For each view in the list...

    foreach (SPView myView in myList.Views)

    {

    // If this is the default view...

    if (myView.DefaultView)

    {

    // Set view to have no toolbar.

    myView.Toolbar = "None";

    myView.Update();

    break;

    }

    }

    myList.Update();

    }

     

     

    Wednesday, August 29, 2007 9:20 PM
  • I have the same problem. I ended up doing

    Code Snippet
    myView.Toolbar = "";

     

     

    The problem now is that if you go to the web part editor and change something in this web part (anything), the toolbar will re-appear.

    Friday, August 31, 2007 5:47 PM
  •  

    This does not work either as you still have a standard toolbar displayed.   The direct DB update is the only way so far I was able to get it to change.  Interesting that it was updateable in SP2003.  Hopefully it is a bug that will be corrected in the coming service pack and we will not need a direct db update.

     

    Bruce VB

     

     

     

     

    Tuesday, September 04, 2007 9:34 PM
  • The property Toolbar setting internal xml text of Node "Toolbar". This ist a bug - your need setting attribute "Type" of "Toolbar" node. Use following code:

     

    SPView view = companyLogosLib.Views["Name of View"];

    System.Reflection.FieldInfo field = view.GetType().GetField("Node", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

    XmlNode node = field.GetValue(view) as XmlNode;

    node.SelectSingleNode("Toolbar").Attributes[0].Value = "None";

    view.Update();

    Friday, September 14, 2007 8:49 AM
  •  

    Cool....

     Very Close but

    Node is a property of SPView so you need a GetProperty instead of GetField

     

    SPView view = companyLogosLib.Views["Name of View"];

    System.Reflection.PropertyInfo Props = view.GetType().GetProperty("Node", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

    XmlNode node = Props GetValue(view) as XmlNode;

    node.SelectSingleNode("Toolbar").Attributes[0].Value = "None";

    view.Update();

     

    This updates the view on the list (which you cannot even do from the UI !!!) .   However if you apply the this view to the ListViewWebPart    lvpart.ViewGuid = view.ID.ToString("P"

    you still have the tool bar on the listview on your webpart page although the base view does not.  This is because the WebPart's view is a copy of the base view's schema and not the actual view.  But  Eugen Lechner has led the way for us and here is the code to update ToolBar of the ListViewWebPart on a web page.

     

    lMgr =OpenWebPartManager("Default.Aspx");

    // Get web Part

    wp = lMgr.WebParts[wp.ID] as WebPart;

    ListViewWebPart lv = (ListViewWebPart)wp;

    // Extract view

    System.Reflection.PropertyInfo ViewProp = lv.GetType().GetProperty("View", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

    SPView spView = ViewProp.GetValue(lv, null) as SPView;

    // This forces a refresh of the views internal xml or the node's cild nodes are not populated

    string txt = spView.SchemaXml;

     

    System.Reflection.PropertyInfo NodeProp = spView.GetType().GetProperty("Node", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

    XmlNode node = NodeProp.GetValue(spView, null) as XmlNode;

    XmlNode tBarNode = node.SelectSingleNode("Toolbar");

    if (tBarNode != null)

    {

    tBarNode.Attributes["Type"].Value = "None";

    spView.Update();

    }

     

     

    As fun as all this Reflection and XML processing is we are still left with a hack like my direct database update from above that updates private properties that may or may not exists later.  Although better it is still unsupported by MS and could break with the next service pack.  What we need is something high tech like

     

    wp = lMgr.WebParts[wp.ID] as WebPart;

    ListViewWebPart lv = (ListViewWebPart)wp;

    lv.View.ToolBarType = "None";

     

    Come on MS.... Throw us a bone here....

     

    Regards

    Bruce VB

    zNetSys

     

     

     

     

    Tuesday, September 18, 2007 3:58 PM
  • While still coupled pretty closely to the current CAML schema, this seems to work just fine:

     

    SPView view = newSite.Lists[listID].Views[new Guid(lvwp.ViewGuid)];

    view.Toolbar = "<Toolbar Position=\"After\" Type=\"None\" />";

    view.Update();

     

    Alternatives could be:

     

    view.Toolbar = "<Toolbar Position=\"After\" Type=\"Standard\" />";

     

    or

     

    view.Toolbar = "<Toolbar Position=\"After\" Type=\"Freeform\"><!-- CAML goes here --></Toolbar>";

     

    Jace B

     

    P.S. -- The reason your "replace" code didn't work in the first place is that the node is optional, and doesn't seems to exist by default.

    Monday, December 03, 2007 7:47 PM
  •  

    The above code doesn't work.  The problem is that the view.Toolbar property isn't the <Toolbar /> node itself, it's the content of the toolbar node.  And since Type is an attribute of the toolbar node, assigning it a new value isn't possible through the view.Toolbar property.  So if your view type is already Freeform, you can use the Toolbar property to change the template, but when it's set to the default value of Standard, any content for the toolbar node seems to be completely ignored.

     

    However, it looks like the SPView.HtmlSchemaXml and the ListViewWebPart.ListViewXml properties are equivalent.  I tried taking the output from view.HtmlSchemaXml of the SPView that I want, replacing <Toolbar Type="Standard" /> with <Toolbar Type="None" />, and updating that webpart in the webpart collection, but after the update the ListViewWebPart.ListViewXml is still null.  Some of the other webparts on the page do have values for ListViewXml but the one I was trying to work with remains null.  I don't know if it's because the Guid of the SPView was still in the ListViewXml that I was passing in or not, and I haven't had time to test further.

    Wednesday, January 09, 2008 10:38 PM
  • Hi Bruce,

    I'm creating a listviewwebpart and adding this to the webpart manager. Then trying to update my webpart view to set the toolbar type to none, the same way you described it in your post.

     

    However my webpart never gets updated.

    Any idea.

     

    Appreciate your reply.

     

    Thanks,

    Vimla

    Thursday, January 10, 2008 8:02 AM
  • Hi jcorra,

    I have the ListViewWebpart added through code that has s standard view and I've trouble changing the view as well.

    You mentioned that you are using the HtmlSchemaXml, can i get some sample on this?

     

    Thanks

    Thursday, January 10, 2008 5:21 PM
  •  

    My code samples are from a Windows Application I threw together to make testing easier (the actual application I'm working on is a custom SPFeatureReceiver class that does site customizations when the Feature is activated, but debugging is much easier from a Windows app than from inside the SPFeature).  I have a text field where I can enter the URL of the site I want to open, a list to select the webpart to work with, a textbox that shows the HtmlSchemaXml property of the selected webpart's current view and any error messages, and a textbox for the XML string to use to update the ListViewXml property of the webpart.

     

    On a side note, using site.GetWebPartCollection() will generate a warning message that SPWebPartCollection has been deprecated, but I found the SPWebPartCollection to be easier to work with than its replacement SPLimitedWebPartManager.  I'm adding new webparts to the page in my SPFeatureReceiver, then doing additional customizations--such as trying to change the ToolBar to Type="None".  SPWebPartCollection.Add() returns the Guid of the newly added webpart, where the AddWebPart() method of the SPLimitedWebPartManager is a void, so you have to do additional work to get a reference to the webpart on the page before you can do any additional work with it.

     

    Code Block

    private void btnConnect_Click(object sender, EventArgs e) {

    this.lstWebParts.Items.Clear();

    try {

    using(SPSite site_collection = new SPSite(this.txtSPSiteURL.Text)) {

    using(SPWeb site = site_collection.OpenWeb()) {

    this.lstWebParts.DataSource = site.GetWebPartCollection("Default.aspx", Microsoft.SharePoint.WebPartPages.Storage.Shared);

    this.lstWebParts.DisplayMember = "Title";

    }

    }

    } catch(Exception ex) {

    this.txtMessage.Text += ex.ToString();

    }

    }

     

    private void lstWebParts_SelectedIndexChanged(object sender, EventArgs e) {

    if(this.lstWebParts.Items.Count > 0) {

    Microsoft.SharePoint.WebPartPages.ListViewWebPart webpart = this.lstWebParts.SelectedItem as Microsoft.SharePoint.WebPartPages.ListViewWebPart;

    if(webpart != null) {

    SPView view = site.Lists[new Guid(webpart.ListName)].Views[new Guid(webpart.ViewGuid)];

    this.txtMessage.Text = view.HtmlSchemaXml;

    } else {

    this.txtMessage.Text = string.Format("{0} is not a ListViewWebPart.", webpart.Title);

    }

    }

    }

     

    private void btnUpdateSchemaXML_Click(object sender, EventArgs e) {

    if(this.lstWebParts.Items.Count > 0) {

    Microsoft.SharePoint.WebPartPages.ListViewWebPart webpart = this.lstWebParts.SelectedItem as Microsoft.SharePoint.WebPartPages.ListViewWebPart;

    if(webpart != null) {

    using(SPSite site_collection = new SPSite(this.txtSPSiteURL.Text)) {

    using(SPWeb site = site_collection.OpenWeb()) {

    try {

    SPWebPartCollection webparts = site.GetWebPartCollection("Default.aspx", Microsoft.SharePoint.WebPartPages.Storage.Shared);

    webpart.ListViewXml = this.txtNewSchemaXML.Text;

    webparts.SaveChanges(webpart.StorageKey);

    } catch(Exception ex) {

    this.txtMessage.Text = ex.ToString();

    }

    }

    }

    }

    }

    }

     

     

    Thursday, January 10, 2008 7:18 PM
  •  

    If you are using the same code then it should work.   One thing you can try is to dispose of the LimitedWebPartManager and recreate it before you reopen the web part to set the toolbar. 

     

    Hope this helps.

     

    Thursday, January 10, 2008 7:26 PM
  • Hi jcorra,

    Thank you for the reply.

    I actually have everything that's the on the sample code.

    But I would like to know how you update the view.HtmlSchemaXml through code iterating through the nodes.

    Because in the sample windows application code, I guess you are manually updating it in the textbox.

     

    Also in my application(windows application) I'm adding a webpart and then get the view of the webpart to update the tool bar type.

    How do you handle this in your custom SPFeatureReceiver class? I guess more or less i'm doing the same in my app.

     

    Thanks,

    Vimala

     

     

    Thursday, January 10, 2008 8:28 PM
  • Vimla-

     

    You could load the SPView.HtmlSchemaXml into an XML document if you want to manipulate it through code.  Sadly, though, it's a read-only property, so you can't update the HtmlSchemaXml of the view directly.  Same with the ToolBarType property.  The only property I've found which is both updateable and contains the <Toolbar /> node is the ListViewXml property of the webpart itself.

     

    However, so far I haven't been able to get that property to update correctly.  For an existing webpart, I tried changing just the toolbar definition to <Toolbar Type="None" /> but when I reload the property after saving it, the ListViewXml still shows <Toolbar Type="Standard" />.  I thought maybe it was because there was still a Guid for the view in the Xml schema definition, and that maybe the definition of the SPView was taking precedence over the changes to the webpart's ListViewXml, so I changed my program to instead add a completely new webpart to the page with no ViewGuid defined and no Guid in the Xml schema definition.  The new webpart gets successfully added to the page, but SharePoint seems to more or less completely ignore the ListViewXml definition I gave it, because the new webpart doesn't have the same fields, any filters, and completely different ordering, none of which match any of the existing views I have on this list.  And worst of all, it was STILL added with a toolbar, but this time <Toolbar Type="Freeform">

     

    It looks like at this point, using System.Reflection or a direct database update are the only options to make this work, for something that seems like it should be simple, considering you can do it manually with 4 clicks.  I think MS needs to put a little more work into the SPView & ListViewWebPart object model.  I definitely agree with Bruce, why can't there just be a ListViewWebPart.View.ToolBarType = "None"?  It can obviously be done somehow, since you can do it manually through the UI, so why make it readonly in the object model?

    Thursday, January 10, 2008 9:02 PM
  • Hi jcorra,

    I guess Toolbar type="FreeForm" works for me ...But it's just that when i add the listviewwebpart programmatically, i can't seem to modify this Standard Tool bar type at all..

     

    So you are adding a new webpart without setting the ViewGuid of the webpart.

    So is it something like this?

     

    ListViewWebPart wp = new ListViewWebPart();
    wp.ZoneID = "Left";

    wp.ListName = list.ID.ToString("B").ToUpper();

    SPWebPartCollection coll =  web.GetWebPartCollection("default.aspx", Storage.Shared);

     

    Is there anything else that you are doing? Do you have to also set the ListViewXml through code?? How do you set the tool bar type?

     

    By the way I'm using the SPLimitedWebPartManager because SPWebPartCollection is Obsolete..Not sure if that makes a difference.

     

     

    Thanks

     

     

     

    Friday, January 11, 2008 2:00 AM
  • Is there a way to remve the toolbar without going through the xml?

     

    Lucy

    Wednesday, March 26, 2008 4:14 PM
  • You only seem to be able to do it either using System.Reflection or through direct database updates, neither of which is a "supported" method of making customizations.

     

    Wednesday, March 26, 2008 5:19 PM
  • Just want to let you all know I got it to work with the follwoing code:

    private static void DisableToolbar(ListViewWebPart lv)

    {

     //  Extract view

     

       System.Reflection.PropertyInfo ViewProp = lv.GetType().GetProperty("View",
        System.Reflection.
    BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

     

       SPView spView = ViewProp.GetValue(lv, null) as SPView;

     

       string txt = spView.SchemaXml;

       System.Reflection.PropertyInfo NodeProp = spView.GetType().GetProperty("Node",
         System.Reflection.
    BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

     

       XmlNode node = NodeProp.GetValue(spView, null) as XmlNode;

       XmlNode tBarNode = node.SelectSingleNode("Toolbar");

     

       if (tBarNode != null)

       {

          XmlAttribute typeNode = tBarNode.Attributes["Type"];

          // make the contents empty so we realy remove the toolbar .....

          // otherwise you might get a different type of toolbar popup when we have a
          // Migrated site from 2.0

          tBarNode.RemoveAll();

          // re-add the type attribute

          tBarNode.Attributes.Append(typeNode);

          // finally set the toolbar to not show....

           typeNode.Value = "None";

        }

    //This forces a refresh of the views internal xml or the node's cild nodes are not populated

     spView.Update();
    }

    Thanks for all the pointers in this thread. I just tought to post the final solution I got working.

    Cheers,

    Marcel

    • Proposed as answer by Frank-Ove Saturday, September 06, 2008 3:20 PM
    Thursday, April 10, 2008 6:39 PM
  • Thank you, Marcel.

    Worked like a charm! :)

    Frank
    Saturday, September 06, 2008 3:19 PM
  • This only seems to work to set the toolbar to none. If I try to set it to Freeform, although in the Web Part Page when I click on properties it does show Summary Toolbar as the selected toolbar but the view I get of the toolbar is that of none. When I click apply then it is ok.
    jasear
    Monday, October 06, 2008 11:48 AM
  •  

    We can achieve same thing by setting following property:

    webPart.SuppressWebPartChrome = true;

    ~ Avinash

    Thursday, November 13, 2008 6:24 AM
  • OH!!SO GOOD! Thanks
    Tuesday, November 18, 2008 5:41 AM
  • Hi,

    One of the problem with following code :

    listViewWebPart.SuppressWebPartChrome = true;

    is that it hide the toolBar in ListViewWebPart as well as in the SPList/SPView from which it is displaying the data
    ( I face this problem, not sure about others :) ).

    So, the other alternative is to add following CSS in our code:

    <style type="text/css">
        .ms-menutoolbar    { display: none; }
    </style>

    Be careful while using the above CSS, because it hide all the ToolBars which uses the  .ms-menutoolbar    CSS class.

    ~ Avinash
    Tuesday, November 25, 2008 5:17 AM
  • Has anyone had any luck with this yet? We have spent almost 1 month trying to find a solution to this problem. We have written a migration tool that imports ListViewWebParts (amongst other things) from SP2003 to MOSS 2007. We are able to add the ListViewWebParts and setup almost all the properties but we are unable to programmatically set the toolbartype.

    Why the SPView.ToolBarType property was made readonly I dont know because if it wasnt it would have been as simple as:

    SPViewToolBarType = "Freeform";

    We tried the solution suggested in here which partially worked for us until we installed some latest updates after which that completely stopped working.

    Can someone please help us with this?
    jasear
    Friday, December 05, 2008 11:02 AM
  • Perhaps we could reverse engineer this? When we go to a sharepoint page and do this on the UI it gets updated correctly. Anyone have any ideas how it is done then? Can someone give me some tips on how I can reverse engineer this?
    jasear
    Wednesday, December 17, 2008 10:12 AM
  • Hi Jasear,

    I am not sure, but you can directly change the ListViewXml programmatically to modify the ToolBarType.
    In my case I modified the empty message thats ListView WebPart displays when it contains no record/SPListItem.
    You can check the code sample at SharePoint's ListViewWebPart.

    In your case, first check the whole XML and then modified the desired node. Use following code to check the ListViewXml :
    Response.Write(oListViewWP.ListViewXml);

    ~ Avinash 
    Wednesday, December 17, 2008 10:44 AM
  • Hi,

    I have had this same problem, and have been following this thread as I've been trying to resolve it. Finally found a solution for this at Tippu's blog(Mubarak Musthafa). This works excellent, and can be used on almost any kind of list. This code sample removes the toolbar and sets it to use the "Summary view". It can easily be modified to just remove the toolbar.

    Tippu’s Blog

    Wrote this to give you a complete sample using Tippu's code to set the toolbar.

    Sample code using an announcement list:

    //Get a reference to the current SPWeb.  
    SPWeb newWeb = SPContext.Current.Web;  
     
    //Create an instance of an announcement list.  
    SPListTemplateType listtemplatetype = SPListTemplateType.Announcements;  
    Guid listID = newWeb.Lists.Add("Announcements""", listtemplatetype);  
    SPList newsList = newWeb.Lists[listID];  
     
    //Get a reference to the SPFile object associated with the default.aspx, using an   
    //SPLimitedWebPartManager object to add the webpart.  
    SPLimitedWebPartManager webPartManager;  
    SPFile page = newWeb.Files["default.aspx"];  
    webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);  
    //Create and add a ListViewWebPart.  
    ListViewWebPart lwp = new ListViewWebPart();  
    lwp.Title = "Announcements";  
    lwp.ListName = newsList.ID.ToString("B").ToUpper();  
    webPartManager.AddWebPart(lwp, "Left", 0);  
    newWeb.Update();  
     
    //Extract the view   
    PropertyInfo ViewProp = lvWebPart.GetType().GetProperty("View", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);  
    SPView spView = ViewProp.GetValue(lvWebPart, nullas SPView;  
     
    //Remove the toolbar and set it to use the "summary view".  
    SetWebPartToolbarAttribute(spView, "Freeform"); 

    Tippu's code:
    private static void SetWebPartToolbarAttribute(SPView spView, String AttributeValue)  
    {  
        string txt = spView.SchemaXml;  
     
        System.Reflection.PropertyInfo NodeProp = spView.GetType().GetProperty("Node", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);  
     
        XmlNode node = NodeProp.GetValue(spView, nullas XmlNode;  
        XmlNode tBarNode = node.SelectSingleNode("Toolbar");  
     
        if (tBarNode != null)  
        {  
            XmlAttribute typeNode = tBarNode.Attributes["Type"];  
            tBarNode.RemoveAll();  
            tBarNode.Attributes.Append(typeNode);  
            typeNode.Value = AttributeValue;  
        }  
     
        if (String.Compare(AttributeValue, "Freeform"true) == 0)  
        {  
            string NewItemString = "";  
            XmlAttribute pos = tBarNode.OwnerDocument.CreateAttribute("Position");  
            pos.Value = pos.Value = "After";  
            tBarNode.Attributes.Append(pos);  
     
            switch (spView.ParentList.BaseTemplate)  
            {  
                 case SPListTemplateType.Announcements:  
                 NewItemString = "announcement";  
                 break;  
                 case SPListTemplateType.DiscussionBoard:  
                 NewItemString = "discussion";  
                 break;  
                 case SPListTemplateType.Links:  
                 NewItemString = "link";  
                 break;  
                 case SPListTemplateType.Tasks:  
                 NewItemString = "task";  
                 break;  
                 case SPListTemplateType.GenericList:  
                 NewItemString = "element";  
                 break;  
                 case SPListTemplateType.DocumentLibrary:  
                 NewItemString = "document";  
                 break;  
            }  
            tBarNode.InnerXml = @"<IfHasRights><RightsChoices><RightsGroup PermAddListItems=""required"" /></RightsChoices><Then><HTML><![CDATA[ <table width=100% cellpadding=0 cellspacing=0 border=0 > <tr> <td colspan=""2"" class=""ms-partline""><IMG src=""/_layouts/images/blank.gif"" width=1 height=1 alt=""""></td> </tr> <tr> <td class=""ms-addnew"" style=""padding-bottom: 3px""> <img src=""/_layouts/images/rect.gif"" alt="""">&nbsp;<a class=""ms-addnew"" ID=""idAddNewItem"" href=""]]></HTML><URL Cmd=""New"" /><HTML><![CDATA["" ONCLICK=""javascript:NewItem(']]></HTML><URL Cmd=""New"" /><HTML><![CDATA[', true);javascript:return false;"" target=""_self"">]]></HTML><HTML>Add a new " + NewItemString + @"</HTML><HTML><![CDATA[</a> </td> </tr> <tr><td><IMG src=""/_layouts/images/blank.gif"" width=1 height=5 alt=""""></td></tr> </table>]]></HTML></Then></IfHasRights>";  
        }  
        spView.Update();  
    }
     

    This does the trick for me. Hope this can be of help to others too.

    ~FrodeM
    Monday, December 22, 2008 1:25 PM
  • The solutions mentioned in this thread will not work once you install the latest infrastructure update which is what happened to us. However thanks to Ton Stegeman and Brian Farhill there is a solution here:

    http://www.tonstegeman.com/Blog/Lists/Posts/Post.aspx?List=70640fe5%2D28d9%2D464f%2Db1c9%2D91e07c8f7e47&ID=90

    Basically, you need to replace:

    string txt = view.ScehamaXml;

    with:

                    webpartView.GetType().InvokeMember("EnsureFullBlownXmlDocument",
                        BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod,
                        null, webpartView, null);

    That is the toolbartype sorted. If you want to be able to set the view then you need to make sure that you set the view first and then call the addwebpart method. If the webpart is already on the page then you need to delete it and then set the properties of your listviewwebpart including the viewguid and then add the web part. Unfortunately, I havent been able to find any other way of setting the view.
    jasear
    Tuesday, January 06, 2009 9:58 AM
  • Hi,
    You will definetly achieve it.
    Some approaches are discussed in the following post:

    http://etechplanet.com/post/2009/02/05/AddingRemoving-toolbar-from-custom-ListViewWebPart.aspx

    Regards,
    Avaneet
    Thursday, February 12, 2009 3:13 PM
  • I've posted a solution to updating the ListViewWebPart Toolbar type at:

    http://spschris.blogspot.com/2009/02/updating-toolbar-type-for-sharepoint.html

    Hope this helps resolve this issue.

    Chris Buchanan
    Solution Developer
    www.redsphere.ca
    Chris
    Friday, February 20, 2009 10:53 PM
  • As I have already mentioned. That solution will not work if you have installed the latest infrasructure update.

    The following solution works:

    http://jasear.wordpress.com/2009/04/05/listviewwebpart-programatically-setting-the-toolbartype-property/
    Visit my blog http://jasear.wordpress.com
    Sunday, April 05, 2009 7:23 PM
  • Hi all,

     I want to share following code which removes tool bar for list view webpart
     I did it based on the inputs provided by you all.
     Thank you all.

      protected override void  CreateChildControls()

      {

     

           SPSite site = new SPSite(SPContext.Current.Site.Url.ToString());

           SPWeb web = site.OpenWeb();

           web.AllowUnsafeUpdates = true;

           SPList list = web.Lists["Name of the List"];

           ListViewWebPart lvwp = new ListViewWebPart();

           lvwp.ListName = list.ID.ToString("B").ToUpper();

           SPView view = list.Views["Name of the View"];

           System.Reflection.PropertyInfo Props = view.GetType().GetProperty("Node", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

           XmlNode node=Props.GetValue(view,null) as XmlNode;

                                                   node.SelectSingleNode("Toolbar").Attributes[0].Value="None";

           view.Update();

           lvwp.ViewGuid = view.ID.ToString("B").ToUpper();

           lvwp.ViewType = ViewType.Html;

           lvwp.GetDesignTimeHtml();

           this.Controls.Add(lvwp);

           base.CreateChildControls();

      }

     

     

     

    Friday, June 19, 2009 1:30 PM
  • The problem I am having with this is that the Toolbar child node doesn't exist.

    I am creating a new SPView on the list, then setting the ListViewWebPart to that view, then I delete it.  but this new view doesn't have a Toolbar child node, and when I try to add it, the ListViewWebPart drops back to use the default View and not my custom view.

    I have tried using the DefaultView as well and removing the ToolBar... but as far as I can see, none of the views are returning a Toolbar child node.

    Any ideas?

    Mark Stokes
    Wednesday, July 01, 2009 9:55 AM
  • OK,

    I finally got my head around this and have created a blog article about it:
    http://sharepointstudio.com/People/MarkStokes/Lists/Posts/Post.aspx?ID=27

    Hope this helps

    Mark Stokes
    http://sharepointstudio.com/
    • Proposed as answer by Mark Stokes Thursday, July 02, 2009 1:06 PM
    Thursday, July 02, 2009 10:04 AM
  • Hi Mark Stokes,

    I tried ur code for removing the toolbar. when i set the toolbar property to 'None'. In listviewwebpart, in place of toolbar it shows text 'None'. Have you also faced the issue?
    Thursday, July 02, 2009 11:59 AM
  • I have not seen this happen in my environment.

    Are you able to post your code here and I will have a look at it.

    Mark

    Thursday, July 02, 2009 1:07 PM
  • Hello


     Franks and Bruce VB1 solutions are working

    I want to mention what is happening  in order to clarify both solutions.

    Actually, List view webpart should be added first to the page. What we normally see and by default is the current view not the one we create.

    Therefore to change the view ex: either remove toolbar or header, w
    e have to use reflection on the actual webpart to get the current view and then modify it.

     to remove header 1) use reflection, 2) spView.ViewHeader = string.Empty;

    to remove toolbar please follow  the provided solution by those two guys I mentioned above.

    Cheers

    Note: Please be aware that if the user go and edit the current view toolbar will show up, as added
             to the list view web part.


    Momo
    Tuesday, November 03, 2009 1:23 AM
  • Hi all,

    Even i was facing the same issues. Searched a lot on net same method to hide the toolbar.

    Finally i got this solution which worked for me well.
    Hope it will help others to save time.

    http://www.etechplanet.com/post/2009/02/05/AddingRemoving-toolbar-from-custom-ListViewWebPart.aspx

    Regards,
    Govind.
    jr software programmer
    Thursday, January 07, 2010 3:14 AM
  • Hello

    If you want to hide or remove the header from list view web part. You have to assign minimal header CAML string to the header view. So that you prevent having an extra closing table at the end of the list view web part.  Here is PowerShell code that I have wrote in order to test this solution :

    $pageUrl  = "http://momo/pages/listViewWebPart .aspx "

    $site = new-object microsoft.sharepoint.spsite

    $web = $site.OpenWeb()

    $file = $web.GetFile('/pages/listViewWebPart .aspx')

    $manager =

    $file.GetLimitedWebPartManager(

    [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

    $manager.WebParts | Format-List Title, Id

    $wp = $manager.WebParts['g_4444']

    $wptype = $wp.GetType()

    $viewProperty = $wptype.GetProperty('View',[Reflection.BindingFlags]'NonPublic,Instance')

    $view = $viewProperty.GetValue($wp,$null)

    $view.ViewHeader = "<HTML><![CDATA[<TABLEID='onetidDoclibViewTbl0]]></HTML><HTML><![CDATA['width='100%'border=0cellspacing=0cellpadding=1rules=rows><TRVALIGN=TOP><FORM>]]></HTML><HTML><![CDATA[</FORM></TR>]]> </HTML>"

    $view.Update()

    $web.Dispose()

    $site.Dispose()

     

    Note : Please replace values of lines in blue by your own values.

    Cheers


    Momo
    Friday, March 12, 2010 9:38 PM
  • Hi Mohamed,

    Thaks for your post.

    I need to change to the listviewwebpart toolbar type to "full toolbar" in my default.aspx page.

    Could you please help me how to change th toolbar type using the Powershell deployment script.

    Thanks Advance

    Suresh

    Wednesday, December 28, 2011 9:53 AM
  • Hi Guys,

    Instead of Listviewwebpart, i am using XlstListViewWebPart start working fine ECB Manu.

    And finally we need to add the below line of the code is also.

    ' Save the changes to the Web Part.
              $webPartManager.SaveChanges($WebParts)

    Cheers

    Suresh

    Friday, December 30, 2011 8:05 AM
  • There are almost fifty posts in this thread from 2007 which had an answer long ago.

    I am therefore locking it.

    Moderator


    SP 2010 "FAQ" (mainly useful links): http://wssv4faq.mindsharp.com/default.aspx
    WSS3/MOSS FAQ (FAQ and Links) http://wssv3faq.mindsharp.com/default.aspx
    Both also have links to extensive book lists and to (free) on-line chapters
    Saturday, December 31, 2011 7:21 AM