Freigeben über


Adding custom SharePoint Toolbar and ToolbarButtons in code

Part 3: Extending your web part to include toolbars

SharePoint toolbars use user controls (.ascx files) to control HTML rendering and layout. This is great if you have an ASPX page to use them on (in fact, you can base your efforts off one of the built in pages in the layouts directory). However, this presents an interesting challenge when you want to create toolbars through assembly code alone.

You'll notice there's no constructor for the two useful classes, Toolbar and ToolbarButton in the Microsoft.SharePoint.WebControls namespace. To get toolbars in your web part, you need to create a control using the Page.LoadControl method, pointing to the relevant user control and casting the results. It’s pretty simple:

         private void CreateToolbar()
        {
            ToolBarButton toolbuttonGrouping =
                 (ToolBarButton)Page.LoadControl("~/_controltemplates/ToolBarButton.ascx");
            toolbuttonGrouping.Text = "Show in Groups";
            toolbuttonGrouping.ImageUrl = "/_layouts/images/TABGEN.gif";
            toolbuttonGrouping.Click += new EventHandler(toolbuttonGrouping_Click);

            ToolBar toolbar = (ToolBar)Page.LoadControl("~/_controltemplates/ToolBar.ascx");
            toolbar.Buttons.Controls.Add(toolbuttonGrouping);

            Controls.Add(toolbar);
        }

        void toolbuttonGrouping_Click(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

This produces the following toolbar, when called from CreateChildControls:

Picture of SharePoint toolbar with one custom button

You can add buttons to the right using Toolbar.RightButtons.Controls collection if you fancy.

P.s. Sorry for the blogging gap – it’s been rather busy lately. At your request, I’m now putting together a full downloadable sample solution for SPGridView, SPMenuField and the Toolbar stuff, complete with grouping, paging and sorting. Check back in a couple of weeks.

Comments

  • Anonymous
    February 24, 2008
    PingBack from http://stevepietrekweblog.wordpress.com/2008/02/24/links-2242008/

  • Anonymous
    February 25, 2008
    The comment has been removed

  • Anonymous
    June 05, 2008
    Why validation is not working when you hit on ToolBarButton?

  • Anonymous
    September 07, 2008
    If you would like to have some paragraphs translated from Polish to English please leave a comment. Post

  • Anonymous
    March 25, 2009
    SharePoint Customizing and Branding Web Content Management-Enabled SharePoint Sites (Part 1 of 3): Understanding

  • Anonymous
    August 13, 2009
    What if you wanted sub items to this menu item?