Friday, January 19, 2007
« ASP.Net Controls, Part 1: Web User Cont... | Main | Hope I don't wear out my delete key this... »

This is part two in a series of posts about ASP.Net Controls.

ASP.Net Controls, Part 2: Composite Custom Controls - some assembly required

Now these controls are able to be designed to have some reuse and life outside one particular project.  The up side is that you can piece together odds and ends from System.Web.Ui.WebControls just how you like them, and as per normal the actual rendering to HTML is left to ASP.Net.

The down side is you just start with a class, descend from WebControl and piece it together in code.

Here's a bare bones sample to illustrate the concept, but first some notes:

  • Import System.ComponentModel for the attributes on the properties.  This is how they display in your Visual Studio properties window
  • Use actual controls as backing variables for the properties.  You want to be holding instances of the controls you will display in your class, and then abstract their properties behind your own properties.
  • CreateChildControls is where you assemble what will eventually be rendered down to the browser by adding to the Controls collection exposed by the base class.
  • Call EnsureChildControls.  A lot.  :-) 
  • This sample control no behaviour.  Use += / AddHandler to wire up your controls to event handlers.  Omitted for clarity.
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace MyProject.Controls
{

    public class CompositeControl : System.Web.UI.WebControls.WebControl
    {

        TextBox txtInput = new TextBox();
        Button cmdSubmit = new Button();
       
        protected override void CreateChildControls()
        {
            EnsureChildControls();

            txtInput.Text = DefaultText;
            Controls.Add(txtInput);

            cmdSubmit.Text = "Submit";
            Controls.Add(cmdSubmit);

            base.CreateChildControls();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
        }

        [Category("Appearance"), DefaultValue("Enter text here")]
        public string DefaultText
        {
            get
            {
                EnsureChildControls();
                return txtInput.Text;
            }
            set
            {
                EnsureChildControls();
                txtInput.Text = value;
            }
        }

    }
}

Comments are closed.