The ASP Column

The Internet Explorer Toolbar Control

George Shepherd

Code download available at:ASPColumn0309.exe(139 KB)

Contents

Toolbar Example
Toolbars and the Designer
Toolbar Events
Examining Toolbar State
Using Toolbars Programmatically
Customizing the Toolbar
The Rendered Code
Conclusion

Over several issues of MSDN® Magazine I've been taking a look at the Microsoft® Internet Explorer Web controls. In the June 2003 issue I looked at the TreeView control, which supports hierarchical representations of data. This time I'll take a look at the last of the Web controls—the Toolbar. Toolbars have been around for some time, providing shortcuts for accessing program features. The Internet Explorer Toolbar control lets you put a toolbar on your ASP.NET Web page, and performs the jobs of rendering the correct tags and managing the toolbar state.

Just as with other server-side controls, toolbars are represented by tags within an ASP.NET page and derive from the class named Microsoft.Web.UI.WebControls.Toolbar. The Internet Explorer Web Toolbar control enables you to provide many of the Windows® toolbar features within a Web page.

Toolbar Example

To illustrate how the Internet Explorer Toolbar works, this month's example displays a string in a variety of fonts and settings. For example, text may appear in one of several colors, styles (bold, italic, or underlined), and sizes (large, medium, or small). Each of these features is selectable from the toolbar using various button, dropdown list, and text controls within the toolbar itself. Figure 1 shows the sample program running.

Figure 1 Changing Font Styles Through the Internet Explorer Toolbar

The Toolbar in Figure 1 shows all the toolbar items an Internet Explorer Toolbar can provide. On the left of the toolbar is an edit box for entering text. The three buttons immediately to the right of the textbox work like radio buttons, allowing you to select one of several exclusive options (that is, the large, medium, or small font). To the right of these buttons are a group of three checkbox-style buttons for selecting up to three inclusive-or operations (that is, the bold, italic, and underline font styles). To the right of the checkbox-style buttons is a dropdown listbox. Finally, there is a regular button for advancing to the next page.

The Internet Explorer server-side toolbar is comprised of a number of toolbar items, each one performing a specific function. The toolbar items are similar to their standalone counterparts (for example, the Button class, the Label class, the Textbox class, and the DropDownList class). Figure 2 lists the toolbar items and the properties they expose.

Figure 2 Toolbar Items and Their Properties

Toolbar Item Description Properties
ToolbarButton Regular button on a Toolbar ID, AccessKey, DefaultStyle, Enabled, HoverStyle, ImageURL, SelectedStyle, TabIndex, Text, ToolTip
ToolbarCheckButton Standard toggle (inclusive OR) ID, AccessKey, AutoPostBack, DefaultStyle, Enabled, HoverStyle, ImageURL, Selected, SelectedStyle, TabIndex, Text, ToolTip
ToolbarCheckGroup Radio button style (exclusive OR) ID, AccessKey, AutoPostBack, DefaultStyle, Enabled, ForceSelection, HoverStyle, Items, SelectedStyle, TabIndex, ToolTip
ToolbarLabel Regular label ID, AccessKey, DefaultStyle, Enabled, ImageURL, TabIndex, Text, ToolTip
ToolbarSeparator Separates items ID, AccessKey, DefaultStyle, Enabled, TabIndex, Text, ToolTip
ToolbarTextBox Textbox on a Toolbar ID, AccessKey, AutoPostBack, BackColor, BorderColor, BorderStyle, BorderWidth, Columns, CssClass, DefaultStyle, Enabled, Font, ForeColor, Height, HoverStyle, MaxLength, ReadOnly, TabIndex, Text, ToolTip, Width
ToolbarDropDownList Combobox on a Toolbar ID, AccessKey, AutoPostBack, BackColor, CssClass, DataMember, DataSource, DataTextField, DataTextFormatString, DataValueField, DefaultStyle, Enabled, Font, ForeColor, Items, TabIndex, Width

Toolbars and the Designer

The easiest and most straightforward way to use the Toolbar control is through the ASP.NET forms designer in Visual Studio® .NET. The Internet Explorer Toolbar includes explicit design support. To use a Toolbar on a Web Form, drag it onto the form as you would any other control. It is initially rendered as a gray box (with some instructions about adding items using the property pane). Figure 3 shows a fresh Toolbar control on a Web Form.

Figure 3 Toolbar Control Placed on a Web Form

Figure 3** Toolbar Control Placed on a Web Form **

The Toolbar object itself includes a number of properties, such as background color, border styles, and fonts. Modifying the appearance of the toolbar is as simple as modifying each of these properties. As most Web controls do, the Toolbar control exposes an AutoPostback property. When AutoPostback is true, every item causes a postback to the server. When it's set to false, each item may be tailored to post back (or not).

Once the Toolbar is in place on the form, you may use the Items property to add toolbar items to it. The dialog is pretty straightforward, and there's nothing unusual you need to watch out for.

Toolbar Events

The Toolbar itself exposes two main events that may be wired up through the designer. The Internet Explorer Toolbar is composed of buttons and other controls that normally have events wired up to them. The constituent controls cannot be connected through the designer, but they can be wired up manually. I'll describe both techniques.

The two events exposed by the Toolbar control (above and beyond the normal complement of Disposed, Load, Init, Prerender, Unload, and DataBinding) are ButtonClick and CheckChange. ButtonClick occurs whenever one of the buttons on the toolbar has been pressed. CheckChange occurs whenever one of the checkbox-style buttons is changed.

You can have the designer write the event-handling code for you by highlighting the toolbar on the form and choosing the event button on the Properties dialog (the event button is represented by the little lightning bolt) and double-clicking in the ButtonClick event box. The designer will stub out a button click event handler in your codebehind page. You may then interrogate the object (the first argument) about the event that just occurred, as shown in the following code:

private void OptionsToolbar_ButtonClick(object sender, System.EventArgs e) { // one way to respond to a button press: ToolbarButton tbbtn; tbbtn = ((ToolbarButton)sender); if(tbbtn.ID == "GoToMainPage") { Server.Transfer("mainpage.aspx"); } }

Alternatively, you may respond to button click events by writing an event handler and manually attaching it to the button when the page is initialized, as shown in Figure 4. The code in Figure 4 shows the font page's OnInit method, which hooks up the MainPageClick event handler to the 11th toolbar item (which happens to the main page button). Notice the signature of the handler—it's defined by the Microsoft.Web.UI.WebControls.ToolbarItemEventHandler delegate from the Internet Explorer Web Controls assembly. It returns a Boolean (rather than the void type that most event handlers return). You should return true if you want the event to bubble and false if you want the event handling to stop here. Responding to the button clicks directly results in tighter code, but then you have to write the handlers yourself.

Figure 4 Responding to a Button Directly

// OnInit called when page is created override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); ToolbarButton MainPageButton; MainPageButton = (ToolbarButton)this.OptionsToolbar.Items[11]; MainPageButton.ButtonClick += new ToolbarItemEventHandler(OptionsToolbar_MainPageClick); base.OnInit(e); } private bool OptionsToolbar_MainPageClick(object sender, System.EventArgs e) { Server.Transfer("mainpage.aspx"); return true; }

Examining Toolbar State

The Toolbar control in this example has its AutoPostback property set to true. Whenever a button is pressed or a control is changed, the Toolbar causes a postback. Once inside the postback, you can easily examine the state of the checkbox and radio buttons. The code download for this column contains the font page's rendering code, which checks each of the font style buttons to render the correct tags. In it, each control is extracted from the Items collection using the numerical index of the control. This is straightforward enough. However, it means that you need to update this code if you decide to insert a control into the toolbar and change the position of the existing subcontrols.

Before I discuss how to create toolbars programmatically, let me say a couple of things about the Render method. Many regular ASP.NET pages are displayed by walking the list of server-side controls on the page and asking each one to render itself (by calling Control.Render). Sometimes pages render by calling Response.Write directly as well. Response.Write places text directly into the output stream of the page, and the font page in the example could easily have been rendered using this method, although that is not recommended for controls.

However, because System.Web.UI.Page derives from System.Web.UI.Control, you can use the HtmlTextWriter class to manage the HTML tags by overriding Render, which you'll see when you look at the code download. The HtmlTextWriter parameter that is passed to the Render method will manage the HTML tags correctly, regardless of the browser that made the request. While it doesn't make any difference in this application (which only manages font styles), using the HtmlTextWriter is very useful when rendering tables and other HTML elements whose syntax varies between HTML versions.

Using Toolbars Programmatically

In addition to developing toolbars via the designer, you may also develop them programmatically. Just imagine a situation in which a toolbar might need to be rendered differently depending on the identity or authorization of the user. When these conditions are determined at run time, it's definitely appropriate to manipulate the toolbar programmatically.

To illustrate runtime toolbar manipulation, my sample signs in users with form-based authentication and then assigns them to an administrator and/or a user role. (Look at the files Web.Config, Login.ASPX, and Global.ASAX in the code download to see how the credentials and roles work.) Once a user is signed in, the example shows the main page of the application with the appropriate toolbars. Figure 5 shows the main page of the application with both toolbars showing (presumably, a user with both a user and administrator role is logged on).

Figure 5 Main Page of App with Two Toolbars

Figure 5** Main Page of App with Two Toolbars **

The main page starts with toolbars (the AdministratorsToolbar and the UsersToolbar) that were added via the designer. The visibility for each of these toolbars is set to false, which means that they won't render. The toolbars are assembled programmatically (based upon the user and his or her role). Figure 6 shows the code for setting up the UsersToolbar, as well as for responding to the button clicks on the toolbar.

Figure 6 Assembling the Toolbars Programmatically

protected void SetupUsers() { string cssString = @"Z-INDEX: 101; LEFT: 170px; POSITION: absolute; TOP: 200px"; UsersToolbar.CssClass = cssString; this.UsersToolbar.AutoPostBack = true; // Users can get news, do email, messaging, fonts ToolbarLabel tblbl = new ToolbarLabel(); tblbl.Text = "Stuff Users can do:"; CssCollection cssc = new CssCollection(@"font-family:Arial; font-weight:bold;background:white;border: solid 1px;color:black"); tblbl.DefaultStyle = cssc; UsersToolbar.Items.Add(tblbl); ToolbarButton tbbtnNews = new ToolbarButton(); tbbtnNews.Text = "News"; tbbtnNews.ID = "News"; UsersToolbar.Items.Add(tbbtnNews); ToolbarButton tbbtnEmail = new ToolbarButton(); tbbtnEmail.Text = "Email"; tbbtnEmail.ID = "Email"; UsersToolbar.Items.Add(tbbtnEmail); ToolbarButton tbbtnMsg = new ToolbarButton(); tbbtnMsg.Text = "Messaging"; tbbtnMsg.ID = "Messaging"; UsersToolbar.Items.Add(tbbtnMsg); ToolbarButton tbbtnFonts = new ToolbarButton(); tbbtnFonts.ID = "Fonts"; tbbtnFonts.Text = "Fonts"; UsersToolbar.Items.Add(tbbtnFonts); UsersToolbar.Visible = true; } // Similar function for the Administrators Toolbar private void Page_Load(object sender, System.EventArgs e) { // Set up all the toolbar items during the first HTTP get, but // not during subsequent posts. if(!this.IsPostBack) { if(User.IsInRole("Administrators")) { SetupAdministrators(); } if(User.IsInRole("Users")) { SetupUsers(); } } } private void UsersToolbar_ButtonClick(object sender, System.EventArgs e) { if(sender is ToolbarButton) { if(((ToolbarButton)sender).ID == "Fonts") { Server.Transfer("fontplay.aspx"); } else if(((ToolbarButton)sender).ID == "Email") { this.LabelWhatsHappening.Text = "Doing email..."; } else if(((ToolbarButton)sender).ID == "Messaging") { this.LabelWhatsHappening.Text = "Doing messaging..."; } else if(((ToolbarButton)sender).ID == "News") { this.LabelWhatsHappening.Text = "Doing news..."; } } }

This code also determines the role of the user and sets up each Toolbar appropriately. It creates and adds each of the buttons to the UsersToolbar. Also, notice that the visible flag is flipped to true for the appropriate Toolbars. The code responds to the Toolbar's ButtonClick event by interrogating the sender of the event in order to find out the cause of the postback.

Customizing the Toolbar

The Toolbar class and each of the items includes a set of Cascading Style Sheet collections for customizing them. If you take a look at the code in Figure 6, you'll notice that it applies the CssCollection class to customize the look of the Toolbar in the SetUpUsers method. The Toolbar and its constituent elements have a default style, a hover style, and a selected style.

The Rendered Code

One of the most interesting aspects of the Toolbar is the HTML it renders. In a downlevel browser, the toolbar is represented using table tags and toolbar buttons are implemented using HREF tags. The dropdown listbox is represented using selection tags within the table. When the client is an uplevel browser, the toolbar is implemented within a file named "/webctrl_client/1_0/toolbar.htc". The file toolbar.htc includes script to enable features such as tooltips and hovering.

Conclusion

This month wraps up my coverage of the Internet Explorer Web controls. The Toolbar control is useful for consolidating related commands (as with the font Toolbar) and it includes good designer support (except for individual control events). And remember, you can also manipulate the Toolbar programmatically when you need that flexibility.

Send your questions and comments for George to  asp-net@microsoft.com.

George Shepherd delivers seminars with DevelopMentor and is an architect of Syncfusion's .NET Windows Forms tools. He is the author of a number of programming books, including Programming with Microsoft Visual C++ .NET (Microsoft Press, 2002), and Applied .NET (Addison-Wesley, 2001). George may be reached at georges@syncfusion.com or georges@develop.com.