Ian Blackburn

October 2005 Entries

CompositeControl vs User Controls - which is less hassle now?

Now that we have the CompositeControl to inherit from in Asp.Net 2, that makes life so much simpler (no more EnsureChildControls milarky), I think there is a compelling reason for developers to consider creating Custom Server Controls where before they would have chosen a User Control and given the reason: "it's less hassle".

Coupled with the better integration in VS2005 (your control projects in your solution are automatically referenced and added to to the toolbox), and the benefits Custom Server Controls bring (miles better design time support, easy distibution amoung projects) then User Controls should only be used for application specific UI (which was always there intention but not always the practice in my experience).

Just look how easy it is to create a RequiredTextBox using a composite control:


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

public class RequiredTextBox : CompositeControl

     {

          private TextBox textBox;

 

          public bool Required

          {

              get

              {

                   if (ViewState["Required"] == null)

                   {

                        ViewState.Add("Required", false);

                   }

                   return (bool)ViewState["Required"];

              }

              set

              {

                   ViewState["Required"] = value;

              }

          }

 

          public string Text

          {

              get

              {

 

                   return textBox.Text;

              }

              set

              {

                    textBox.Text = value;

              }

          }

          protected override void CreateChildControls()

          {

              textBox = new TextBox();

              textBox.ID = this.UniqueID;

              Controls.Add(textBox);

              if (this.Required)

              {

                   RequiredFieldValidator validator = new RequiredFieldValidator();

                   validator.ControlToValidate = textBox.ID;

                   validator.ErrorMessage = "Required";

                   Controls.Add(validator);

              }

 

          }

     }