Web Part with Toolbar
A web part that has its own toolbar with different controls added to it programmatically is easy to build.
1) Create a web part and override CreateChildControls and Render methods:
- public class WPT : WebPart {
- protected ToolBar tlb;
- protected override void CreateChildControls()
- {
- base.CreateChildControls();
- tlb = (ToolBar)Page.LoadControl("/_controltemplates/ToolBar.ascx");
- tlb.ID = "NavNodesTB";
- tlb.Template_Buttons = new BtnTemplate();
- Controls.Add(tlb);
- }
- protected override void Render(HtmlTextWriter writer)
- {
- RenderChildren(writer);
- }
- }
2) Create the BtnTemplate class that implements ITemplate interface. Add all the controls you want to show up on the toolbar
- public class BtnTemplate : ITemplate
- {
- DropDownList ddlNumbers;
- HyperLink tlBarLink;
- void ITemplate.InstantiateIn(Control container)
- {
- tlBarLink = new HyperLink();
- tlBarLink.ID = "idClickMeText";
- tlBarLink.Text = "Click Me";
- tlBarLink.ToolTip = "Click Me";
- tlBarLink.NavigateUrl = "javascript:alert('Hello World!')";
- ddlNumbers = new DropDownList();
- ddlNumbers.ID = "idNumbers";
- ddlNumbers.Load += new EventHandler(ddlNumbers_Load);
- ddlNumbers.AutoPostBack = false;
- container.Controls.Add(tlBarLink);
- container.Controls.Add(ddlNumbers);
- }
- void ddlNumbers_Load(object sender, EventArgs e)
- {
- ddlNumbers.Items.Clear();
- ddlNumbers.Items.Add(new ListItem("One"));
- ddlNumbers.Items.Add(new ListItem("Two"));
- ddlNumbers.Items.Add(new ListItem("Three"));
- }
- }
3) Finally,deploy your web part and you are pretty much done! Here is how your web part looks like.
Source Code can be downloaded here.
Update 13/Sep/2008: Another way of adding toolbar is now documented here.
Categories: MOSS 2007
Thank you for this example. I’ve been trying to find a way to do this in code for about 6 months. So far I’ve only been able to find descriptions of how to do it declaratively.
Glad to hear that.Stay tuned , I am posting more stuff in this area soon!
very usefull example, i was looking every where to find this !!
thanks
thank u so much…. exactly this is what i want
Is there anyway I can see what “/_controltemplates/ToolBar.ascx” looks like?
nevermind
Great post Reza, exactly the interface elements I was looking for.
For those who have subscribed to this post, here is another way of adding toolbars to your Web parts:
https://blogs.devhorizon.com/reza/?p=670
Great post…
Thanks Reza.
Hey this an awesome post.. cool one, thanks