Export (0) Print
Expand All

Walkthrough: Creating a Web Custom Control

Visual Studio .NET 2003

If none of the existing ASP.NET server controls meet the requirements of your application, you can create a custom control by deriving from one of the base control classes. These classes provide all the basic functionality of server controls, so you can focus on programming the features you need.

In this walkthrough, you will use the code for a custom Label control that is included by default in the Web Control Library template. This control is derived from the WebControl class and behaves the same as a standard Label control with the added property of rendering the value of the Text property as a hyperlink. To complete the walkthrough, you will perform these procedures:

  • Create two projects in the same solution — one for the custom Label control, and one for a Web Forms page to consume and test the control.
  • Add the control to the Toolbox.
  • Consume the custom control by adding it to the Web Forms page.
  • Create a custom designer for the control.
  • Test the control in the browser.
    Note   The Web Control Library template is not available in the Standard Edition of Visual Basic and Visual C# .NET. For more information, see Visual Basic Standard Edition Features or Visual C# Standard Edition Features.

The emphasis in this walkthrough is not on writing code for the control, but rather on what to do to make a control once the code is written.

Creating the Projects

The first step is to start a new project with the custom control template and build the control.

To create the custom control

  1. On the File menu, point to New, and then click Project.

    The New Project dialog box appears.

  2. In the Project Types pane, choose either Visual Basic Projects or Visual C# Projects. Select Web Control Library in the Templates pane.
  3. Change the Name to CustomLabel and click OK.

    The new project is created, and WebCustomControl1 opens in the Code Editor.

    Code for a custom Label control is included in the Web Control Library template by default. This is the control you will use in this walkthrough.

  4. On the Build menu, click Build CustomLabel to compile the control.

    The control is compiled as CustomLabel.dll. By default, it is created in the Bin folder inside the CustomLabel project folder.

  5. Save the file.

Now that the control has been created, you will add a Web Forms page to the same solution so that the page is convenient for testing the control.

To create the Web Forms page

  1. On the File menu, point to Add Project, and then click New Project.

    The Add New Project dialog box appears.

  2. In the Project Types pane, choose either Visual Basic Projects or Visual C# Projects. Select ASP.NET Web Application in the Templates pane.
  3. In the Location box, enter the complete URL for your application, including http://, and the name of the server. The last part of the URL is the name of your project; for this walkthrough, name your project LabelWebForm. The Web server must have IIS version 5 or later and the .NET Framework installed on it. If you have IIS on your computer, you can specify http://localhost for the server. (If you normally use a proxy server to access the Internet, you might need to configure Internet Explorer to bypass the proxy server in order to use localhost.)
  4. Click OK.

    The new project is created, and WebForm1 opens in the designer.

  5. Save the project.

Adding the Control to the Toolbox

Now that your control has been compiled and you have a Web Forms page ready to test it, you can add the control to the Toolbox so it will be readily available for use.

To add your control to the Toolbox

  1. On the Tools menu, click Add/Remove Toolbox Items.
  2. On the .NET Framework Components tab of the Customize ToolBox dialog box, click the Browse button. Find CustomLabel.dll, select it, and click Open to add WebCustomControl1 to the list of components in the Customize Toolbox dialog box.
  3. Select WebCustomControl1 in the list of .NET Framework components and click OK. WebCustomControl1 is added to the Toolbox.

When you are finished, you should see an icon on the toolbar that looks like this:

Aa728786.vbcustomcontrolontoolbox(en-us,VS.71).gif

The next step is to test the control in the page.

To add the control to the Web Forms page and test it

  1. Open WebForm1 in Design view and drag WebCustomControl1 from the Toolbox to the page.

    The control's default rendering, which is simply the name of the control followed by its ID, appears in the Design view.

  2. Switch to HTML view, and verify that an @ Register directive for the control's assembly is added to the page's HTML, with TagPrefix "cc1".
  3. Set the Text property of the control to Hello.

    The control's appearance in Design view is updated to show the new text.

Next, you are going to customize the control, so you need to remove it from the Toolbox.

To remove the control from the Toolbox

  1. Right-click WebCustomControl1 in the Toolbox and click Delete on the shortcut menu. This action will not delete the control from the project, only from the Toolbox.
  2. Close the Web Forms page without saving.

The custom Label control is now functional, but it's not very attractive and the tag is not distinctive in the code. The next step is to individualize the control.

Individualizing the Control

The control is using the default icon in the Toolbox and the default tag prefix "cc1". To make the control more easily identifiable, change the tag prefix and create a new icon.

To change the tag prefix

  1. Under the CustomLabel project in Solution Explorer, double-click AssemblyInfo to open the AssemblyInfo file in the designer. Add an Imports statement (in Visual Basic) or using statement (in Visual C#) at the top of the AssemblyInfo page:
    ' Visual Basic
    Imports System.Web.UI
    
    // C#
    using System.Web.UI;
    
  2. Add an Assembly: TagPrefix attribute to the list of assembly attributes. This will specify the new TagPrefix for the CustomLabel control, in this case xxx.
    ' Visual Basic
    <Assembly: TagPrefix("CustomLabel", "xxx")>
    
    //C#
    [assembly: TagPrefix("CustomLabel", "xxx")]
    

To create a new icon

  1. Select the CustomLabel project in Solution Explorer. On the Project menu, click Add New Item.

    The Add New Item dialog box appears.

  2. Select Bitmap File in the Templates pane, change the Name to WebCustomControl1.bmp, and click Open. The new bitmap file appears in Solution Explorer and opens in the designer.
    Note   For this walkthrough, the name of the icon file name must match that of the control class exactly (WebCustomControl1), including capitalization.
  3. In the Properties window, change both the Height and Width properties of the bitmap to 16. Icons must be 16 by 16 pixels in size.
  4. Draw a distinctive design on the bitmap, using several colors, so you can recognize the icon.
  5. Save and close the bitmap file.
  6. Select WebCustomControl1.bmp in Solution Explorer. In the Properties window, change the Build Action property to Embedded Resource.
  7. Select the CustomLabel project in Solution Explorer. On the Build menu, click Rebuild CustomLabel.
  8. Save all your work.

When you add the control to the Toolbox now, the icon you created will show up next to the control name. When you consume the control on your Web Forms page, the control's HTML tag will contain the identifying prefix that you specified.

To consume the custom control

  1. Add WebCustomControl1 to the Toolbox again.

    The control appears with the icon you created. Depending on your settings, it may appear under the General tab of the Toolbox.

  2. Reopen the Web Forms page named WebForm1 and drag the control onto it.
    Note   The Text property has reverted to the default, because you closed the Web Forms page without saving earlier.
  3. Switch to HTML view and verify that the TagPrefix attribute of the @ Register directive is xxx.
  4. Because you are going to make another modification to the control, delete WebCustomControl1 from the Web Forms page, but leave it in the Toolbox.

Your custom control is now fully functional and individualized, but its appearance on the design surface is not very helpful. To make the control look better, you will add a custom designer to it.

Creating a Custom Designer

Designers are classes that allow you to modify the design-time appearance and behavior of components and controls. Although the usual goal of any WYSIWYG form designer is to minimize differences between design-time and run-time appearance, at times special design-time cues are necessary. For more information, see Custom Designers.

In this walkthrough, you will implement a custom designer that causes the custom control to render its text as a hyperlink.

To create a custom designer for the control

  1. Select the CustomLabel project in Solution Explorer.
  2. On the Project menu, click Add Reference and add a reference to System.Design.dll.
  3. On the Project menu, click Add New Item.

    The Add New Item dialog box appears.

  4. Select Class in the Templates pane, change the Name to SampleDesigner, and click Open. The new class file appears in Solution Explorer and opens in the designer.
  5. Add code that overrides the base class's GetDesignTimeHtml method. This method is called at design time to get the representation of your control. In the overridden method, do the following:
    1. Get the Text property of the custom control.
    2. If the Text property has been set (that is, it's not an empty string), create a new Hyperlink control, set its properties to match the original control, and call the Hyperlink control's Render method.

    The end result is that the Hyperlink control is displayed in the designer using the value of the Text property.

    The code to perform these steps looks like the following, which is a complete listing of the SampleDesigner file:

    ' Visual Basic
    Imports System
    Imports System.IO
    Imports System.Web
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.Design
    
    Public Class SampleDesigner
        Inherits System.Web.UI.Design.ControlDesigner
    
        Public Overrides Function GetDesignTimeHtml() As String
            ' Component is the control instance, defined in the base
            ' designer
            Dim ctl As WebCustomControl1 = CType(Me.Component, _
                WebCustomControl1)
            If (ctl.Text <> "") Then
                Dim sw As New StringWriter()
                Dim tw As New HtmlTextWriter(sw)
                Dim placeholderlink As New HyperLink()
    
                ' put control text into the link's Text
                placeholderlink.Text = ctl.Text
                placeholderlink.NavigateUrl = ctl.Text
                placeholderlink.RenderControl(tw)
    
                Return sw.ToString()
            Else
                Return Me.GetEmptyDesignTimeHtml()
            End If
        End Function
    End Class
    
    // C#
    
    using System;
    using System.IO;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.Design;
    
    namespace CustomLabel
    {
       public class SampleDesigner : System.Web.UI.Design.ControlDesigner 
       {
    
          public override string GetDesignTimeHtml() 
          {
          // Component is the control instance, defined in the base
          // designer
          WebCustomControl1 ctl = (WebCustomControl1 ) Component;
    
          if (ctl.Text != "" && ctl.Text != null)
          {
             StringWriter sw = new StringWriter();
             HtmlTextWriter tw = new HtmlTextWriter(sw);
    
             HyperLink placeholderLink = new HyperLink();
    
             // put control text into the link's Text
             placeholderLink.Text = ctl.Text;
             placeholderLink.NavigateUrl = ctl.Text;
             placeholderLink.RenderControl(tw);
    
             return sw.ToString();
          }
          else
             return GetEmptyDesignTimeHtml();
          }
       }
    }
    
  6. Open WebCustomControl1.vb or WebCustomControl1.cs (depending on the language you are using) in the designer, and add this attribute to the attribute list just before the WebCustomControl1 class declaration:
    Designer("CustomLabel.SampleDesigner, CustomLabel")
    

    The WebCustomControl1 class declaration should look like this:

    ' Visual Basic
    <Designer("CustomLabel.SampleDesigner, CustomLabel"), _
    DefaultProperty("Text"), ToolboxData("<{0}:WebCustomControl1 _
    runat=server></{0}:WebCustomControl1>")> Public Class WebCustomControl1
    
    // C#
    [Designer("CustomLabel.SampleDesigner, CustomLabel"), DefaultProperty("Text"), ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]
    public class WebCustomControl1 : System.Web.UI.WebControls.WebControl
    
  7. On the Build menu, click Build Solution so that both projects are built.
  8. Save all, and close all the open files.

Testing the Control

To test that the Text property works correctly

  1. Open WebForm1 in the designer.
  2. Drag WebCustomControl1 from the Toolbox onto the page.
  3. Set the Text property of your Web custom control to Hello. The text should appear as a hyperlink on the Web Forms page.
  4. Save WebForm1.

To test the control in a browser

  1. Select WebForm1 in Solution Explorer. On the File menu, click View in Browser.
  2. Verify that Hello shows up in the browser. The text looks like a label, not like a hyperlink.
    Note   At design time in Visual Studio, your code always runs fully trusted, even if the code will eventually be in a project where it would receive less than full trust at run time. This means that your custom control might work properly when you are testing it on your own computer, but might fail due to lack of adequate permissions in a deployed application. Be sure to test your controls in the security context in which they will run in real-world applications.

See Also

Developing ASP.NET Server Controls | Recommendations for Web User Controls vs. Web Custom Controls | Overview of Web Application Security Threats

Show:
© 2014 Microsoft