How To Create Composite Control

ASP.NET includes the TextBox control and the Validation controls which can be combined together to perform user input validation. The restriction is that the developer has to use two different controls to perform a simple validation. In this post are going to create a custom TextBox control which will use Required field validation controls and reduce the complexity of using multiple controls.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AspTextBox
 [ToolboxData("<{0}:AspTextBox runat=server></{0}:AspTextBox>")]
 public class AspTextBox : CompositeControl, INamingContainer
     private TextBox _myTextBox = new TextBox();
     private RequiredFieldValidator _myRFV = new RequiredFieldValidator();
     protected override void OnInit(EventArgs e)
         _myTextBox.ID = this.UniqueID;
         _myRFV.ControlToValidate = _myTextBox.ID;
         _myRFV.Display = ValidatorDisplay.Dynamic;
         _myRFV.EnableClientScript = true;

     public bool isRequired
         get { return _myRFV.Enabled; }
         set { _myRFV.Enabled = value; }

     public String ErrorMessage
         get { return _myRFV.ErrorMessage; }
         set { _myRFV.ErrorMessage = value; }

     protected override void CreateChildControls()

     protected override void Render(HtmlTextWriter writer)
         if (_myRFV.IsValid == false) { writer.WriteBreak(); }


How to use

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<%@ Register Assembly="AspTextBox" Namespace="AspTextBox" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
  <form id="form1" runat="server">
  <cc1:AspTextBox ErrorMessage="Textbox is Required " isRequired="true" ID="AspTextBox1"
      runat="server" />
  <asp:Button ID="Button1" runat="server" Text="Validate" />

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads