Derived Custom Controls in ASP .Net using C#


Custom controls can also be created by deriving from an existing control. This is done when an existing control serves most of the purposes, but lacks in one or few small features. This can be created as follows.

Creating a Derived Custom Control:

Create a new project of type Web Control Library. Add a new class file named as DerivedControl.cs. We do not need the default webcustomcontrol1.cs file. This webcustomcontrol1.cs file can be deleted.

This sample explains how to create a Command Button with a Green Back Ground Color. In the DerivedControl.cs, add the following code. The same idea can be used to extend any other control with different features.

using System;
using System.Web.UI.WebControls;

namespace DerivedControlLibrary
{

/// <summary>
/// Summary description for DerivedControl.
/// </summary>
public class DerivedControl : Button
{

public DerivedControl()
{
//
// TODO: Add constructor logic here
//
this.BackColor = System.Drawing.Color.Green;
}

}
}

The above creates a very simple Command Button class which contains a Green background color and named as DerivedControl. The above code is more than sufficient if we do not plan to add any other feature for customization.

Build the Project and the Web Control Library project will be built as a .dll file. This can now be used as a full fledged control by referencing in Visual C# Web Projects.

Using the Derived Control:

Using the control created above is straight forward. After referencing and adding to the Visual Studio .Net toolbox, the control can be used with just a drag ‘n’ drop. After it is put on the web form, it is like any other normal control found in System.Web.UI.WebControls namespace.