5.2. Creating a Customizable Navigation Bar

Problem

You want to create a navigation bar that lets you add or remove items without changing code so you can reuse the navigation bar in multiple applications.

Solution

Create an XML document containing the items that will be displayed in the navigation bar, and then create a user control that uses the contents of the XML document to provide the required customization.

To create the user control:

  1. Create a file with a .ascx extension.

  2. Place the @ Control directive at the top of the file.

  3. Add a DataList control configured to render a table with an ItemTemplate defining the cells in the table.

In the code-behind class for the control, use the .NET language of your choice to:

  1. Create a user control code-behind class that inherits from the UserControl class.

  2. (Optional) Establish properties for the control that will provide the ability to control programmatically the basic look of the navigation bar, such as its background color.

To use the user control in an ASP.NET page:

  1. Register the control by using the @ Register directive at the top of the page.

  2. Place the tag for the user control in the HTML where you want the control rendered.

The output of a test page demonstrating a typical navigation bar user control is shown in Figure 5-2. Example 5-7 shows the XML document we created to define the contents of the navigation bar. Example 5-8 shows the .ascx file for the user control. Examples 5-9 and 5-10 show the VB and C# code-behind files for the user control. ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.