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:
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.
Add a new class, CompositeControl.cs, to the project. Then delete the WebCustomControl1.cs file.
Enter the following code for the CompositeControl.cs class:
public class CompositeControl : Control, INamingContainer
// 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
// 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
ViewState["MinValue"] = value;
[Category("Behavior"), Description("Maximum value")]
public int MaxValue
ViewState["MaxValue"] = value;
// Handle the constituent control event
public void btnClick(Object sender, EventArgs e)
System.Random r = new System.Random();
// Generate a new random value
intValue = r.Next(Convert.ToInt32(ViewState["MinValue"]),
// Find the constituent label control
Label lbl = (Label) Controls;
// Make sure the controls really exist
// And set the text to display
lbl.Text = intValue.ToString();
Open the AssemblyInfo.cs file. Scroll down in the file and change the AssemblyVersion attribute as shown here:
Build the Example8_2 project.
Add a new Visual C# ASP.NET Web Application project named Example8_2Test.
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.
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.
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
// 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:
Add a new Visual C# Web Control Library project named Example8_3 to the solution.
Rename the WebCustomControl1.cs class CustomWebControl.cs. Open the CS file and change all occurrences of WebCustomControl1.cs to CustomWebControl.cs instead.
Open the CustomWebControl class and add the following code to it:
private bool bold;
public bool Bold
bold = value;
Modify the render method as shown here:
protected override void Render(HtmlTextWriter output)
//Preserve grid positioning information
System.Collections.IEnumerator enumerator =
//Render the control
Open the AssemblyInfo.cs file. Scroll down the file and change the AssemblyVersion attribute as shown here:
Build the Example8_3 project.
Add a new Visual C# ASP.NET Web Application project named Example8_3Test.
Customize the Components tab in the toolbox to add the CustomWebControl control (present in Example8_3.dll).
Drag the CustomWebControl control from the toolbox and drop it on the Web form.
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.
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:
Specifies the name of a property that is the default property for the control
Provides the default HTML the control will generate when it is dropped on a form
Specifies whether the property can participate in data binding
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.