Skip to main content

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
{
 [DefaultProperty("Text")]
 [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)
     {
         base.OnInit(e);
    
     
         _myTextBox.ID = this.UniqueID;
         _myRFV.ControlToValidate = _myTextBox.ID;
         _myRFV.Display = ValidatorDisplay.Dynamic;
         _myRFV.EnableClientScript = true;
         Controls.Add(_myRFV);

     }
     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()
     {
         this.Controls.Add(_myTextBox);
         this.Controls.Add(_myRFV);
     }

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


}
<%@ 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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <cc1:AspTextBox ErrorMessage="Textbox is Required " isRequired="true" ID="AspTextBox1"
      runat="server" />
  </br>
  <asp:Button ID="Button1" runat="server" Text="Validate" />
  </form>
</body>
</html>

Comments

Popular posts from this blog