Creating and Using Web Custom Controls






Creating and Using Web Custom Controls

Web custom controls provide a more flexible (and more complex) alternative to Web user controls for reusing user interface functionality on Web forms. The following sections show you three basic ways to create a Web custom control.

Creating a Composite Control

A composite control is a Web custom control composed of two or more standard Web server controls. Take the following steps to create a new composite control consisting of a TextBox control and a Button control:

  1. Add a new project to the solution. Select the Visual C# Projects project type and create a new Web Control Library project named Example8_2.

  2. Add a new class, CompositeControl.cs, to the project. Then delete the WebCustomControl1.cs file.

  3. Enter the following code for the CompositeControl.cs class:

    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.ComponentModel;
    
    namespace Example8_2
    {
        public class CompositeControl : Control, INamingContainer
        {
            public CompositeControl()
            {
                // Set default values for persisted properties
                ViewState["MinValue"] = 0;
                ViewState["MaxValue"] = 1000;
            }
            protected override void CreateChildControls()
            {
                // Create the constituent controls
                Label lbl = new Label();
                Button btn = new Button();
                // Set initial properties
                lbl.Height = Unit.Pixel(25);
                lbl.Width = Unit.Pixel(75);
                lbl.Text = "0";
                btn.Height = Unit.Pixel(25);
                btn.Width = Unit.Pixel(75);
                btn.Text = "Go";
                // Add them to the controls to be rendered
                Controls.Add(lbl);
                Controls.Add(btn);
                // Attach an event handler
                btn.Click += new EventHandler(btnClick);
            }
    
            // Public properties to display in the Properties window
            [Category("Behavior"), Description("Minimum value")]
            public int MinValue
            {
                get{
                    return Convert.ToInt32(ViewState["MinValue"]);
                }
                set{
                    ViewState["MinValue"] = value;
                }
            }
            [Category("Behavior"), Description("Maximum value")]
            public int MaxValue
            {
                get{
                    return Convert.ToInt32(ViewState["MaxValue"]);
                }
                set{
                    ViewState["MaxValue"] = value;
                }
            }
    
            // Handle the constituent control event
            public void btnClick(Object sender, EventArgs e)
            {
                System.Random r = new System.Random();
                int intValue;
               // Generate a new random value
               intValue = r.Next(Convert.ToInt32(ViewState["MinValue"]),
                   Convert.ToInt32(ViewState["MaxValue"]));
               // Find the constituent label control
               Label lbl = (Label) Controls[0];
               // Make sure the controls really exist
               this.EnsureChildControls();
               // And set the text to display
               lbl.Text = intValue.ToString();
            }
        }
    }
    
  4. Open the AssemblyInfo.cs file. Scroll down in the file and change the AssemblyVersion attribute as shown here:

    [assembly: AssemblyVersion("1.0")]
    
  5. Build the Example8_2 project.

  6. Add a new Visual C# ASP.NET Web Application project named Example8_2Test.

  7. Select the Components tab in the toolbox. Right-click the tab and select Add/Remove Items. Then click the Browse button and browse to the Example8_2.dll file. Click Open and then click OK. This adds the CompositeControl control to the toolbox.

  8. Drag CompositeControl from the toolbox and drop it on the Web form. Access the Properties window for the control and set the MinValue property to 500 and the MaxValue property to 1500.

  9. Set the Example8_2Test project as the startup project for the solution and run the project. The composite control will render as a label and a button in the browser. Click the button to display a random number between 500 and 1,500.

The CompositeControl control in the previous steps uses the ViewState container to store property values that need to be persisted across round trips to the browser. ViewState enables you to automatically read existing values from a hidden value that is sent as part of a postback. Using ViewState is a necessity for values that are required for postback processing (such as the minimum and maximum values, in this case).

ASP.NET automatically calls the CreateChildControls() method when it's time to render the control. In this procedure, the composite control creates new instances of the server controls it will contain, sets their properties, and adds them to its own Controls collection. This is also the point at which any event handlers can be attached.

Finally, the event handler in the previous steps demonstrates how you can retrieve a control from the collection of constituent controls to continue working with it. Controls in the collection are numbered, starting at zero, in the order in which they were added to the collection. Note also the call to the EnsureChildControls() method. This method should be used to protect any access to properties of the child controls; it causes the code to exit if the control does not exist for some reason.

Creating a Derived Control

Another way to create a Web custom control is to derive the control from an existing Web server control. For example, the following code segment creates a new custom control, CustomTextBox, which is derived from the TextBox control:

public class CustomTextBox : TextBox
{
    public CustomTextBox()
    {
       // Change the BorderColor and BorderStyle
       this.BorderColor = System.Drawing.Color.Red;
       this.BorderStyle = BorderStyle.Dashed;
     }
}

Derived custom controls are useful in situations in which you want behavior very much like that of a built-in server control. In the previous example, the only behavior added by the CustomTextBox control is the specific default display of the control's border style and color; all the other methods, properties, and events are inherited directly from the original TextBox control.

Creating a Control from Scratch

The third way to create a Web custom control is to create the control from scratch by deriving it from the WebControl class and writing code to handle the rendering and other tasks, rather than depending on existing controls. Follow these steps to create a control from scratch:

  1. Add a new Visual C# Web Control Library project named Example8_3 to the solution.

  2. Rename the WebCustomControl1.cs class CustomWebControl.cs. Open the CS file and change all occurrences of WebCustomControl1.cs to CustomWebControl.cs instead.

  3. Open the CustomWebControl class and add the following code to it:

    private bool bold;
    [Category("Appearance")]
    public bool Bold
    {
        get{
              return bold;
        }
        set{
              bold = value;
        }
    }
    
  4. Modify the render method as shown here:

    protected override void Render(HtmlTextWriter output)
    {
        //Preserve grid positioning information
        System.Collections.IEnumerator enumerator = 
            this.Style.Keys.GetEnumerator();
        while(enumerator.MoveNext())
            output.AddStyleAttribute((string)enumerator.Current,
                this.Style[(string)enumerator.Current]);
        //Render the control
        output.RenderBeginTag(HtmlTextWriterTag.Div);
        if (bold)
        {
            output.RenderBeginTag(HtmlTextWriterTag.B);
            output.Write(Text);
            output.RenderEndTag();
        }
        else
            output.Write(Text);
        output.RenderEndTag();
    }
    
  5. Open the AssemblyInfo.cs file. Scroll down the file and change the AssemblyVersion attribute as shown here:

    [assembly: AssemblyVersion("1.0")]
    
  6. Build the Example8_3 project.

  7. Add a new Visual C# ASP.NET Web Application project named Example8_3Test.

  8. Customize the Components tab in the toolbox to add the CustomWebControl control (present in Example8_3.dll).

  9. Drag the CustomWebControl control from the toolbox and drop it on the Web form.

  10. Invoke the Properties window and set the Bold property of the control to true. Then set the Text property of the control to This is my custom control.

  11. Set the project as the startup project for the solution and run the project. You should see the text from the control displayed in bold on the resulting HTML page.

The previous steps demonstrate the Render() method, which is called to draw text in both design and run modes. Because this control implements its own version of the Render() method, it can display text easily in either mode. Note also the use of the RenderBeginTag() and RenderEndTag() methods to add HTML markup to the control's output.

You can also see some new attributes at both the class and the property level, including the following:

  • DefaultProperty— Specifies the name of a property that is the default property for the control

  • ToolboxData— Provides the default HTML the control will generate when it is dropped on a form

  • Bindable— Specifies whether the property can participate in data binding

  • DefaultValue— Specifies the default value for the property on a new instance of the control

Custom Control Choices

The following are some points to consider as you decide which architecture to implement for a particular control:

  • Web user controls can be used only in the same project that contains their ASCX file, so they're not well suited for controls that need to be used across many projects.

  • Web user controls are much easier to create than Web custom controls.

  • Web user controls don't support a good representation at design time. Web custom controls can be represented with high fidelity at design time, although you might need to write additional code to do so.

  • Web user controls cannot be added to the Visual Studio .NET toolbox, whereas Web custom controls can be added to the toolbox.

  • Web custom controls are better suited than Web user controls to dynamic layout tasks in which constituent controls must be created at runtime.

  • Composite custom controls are a good choice when you have a group of controls that must be repeated consistently on the user interface of an application.

  • Derived custom controls are a good choice when you want most of the functionality of an existing server control with only a few changes.

  • Writing a Web custom control from scratch provides the most flexibility and control over the generated HTML.


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows