Howto: Create a Custom Control in ASP.NET (C#)

October 30, 2007 12:34 by Dominick

Introduction

Creating custom controls can save you a lot of time and effort when building an application. The built-in sever controls provided can do just about anything you need them to, but sometimes it takes a great deal of coding (hacking) to make it do exactly what you want it to do. Consider the possibility that you need a textbox control that you would like to be able to assign a readony property to it so it either renders as a regular textbox if false or plain text if true. You may also want a textbox that will cause it's on "OnTextChanged" to bubble up in the "GridViewCommandEvent" of a Gridview control. By default the textbox does not support that.

Afterwards there will be Cake

Create a new Web Control Library project within the solution you want to add the control to. Here is the location to do so in my Visual Studio installation.



Visual Studio has created a file called "WebCustomControl1.cs" within that project. You can rename it to whatever you like. This file is where you can insert the code that I'll show below. I'm going to show you the entire code right now. I've put some comments in to explain what's going on. Just copy and paste this code inside the cs file.

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

namespace CustomControls.UI.Controls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:CustomTextBox runat=server></{0}:CustomTextBox>")]
    public class CustomTextBox : TextBox //with this you can override all the normal "stuff" within the textbox control
    {

       //Here are the properties that will be used for the command event

        [Bindable(true)]
        [Category("Custom")]
        [DefaultValue("")]
        [Localizable(true)]
        public string CommandName
        {
            get
            {
                string s = ViewState["CommandName"] as string;
                return s == null ? String.Empty : s;
            }
            set
            {
                ViewState["CommandName"] = value;
            }
        }

        [Bindable(true)]
        [Category("Custom")]
        [DefaultValue("")]
        [Localizable(true)]
        public string CommandArgument
        {
            get
            {
                string s = ViewState["CommandArgument"] as string;
                return s == null ? String.Empty : s;
            }
            set
            {
                ViewState["CommandArgument"] = value;
            }
        }

        [Bindable(true)]
        [Category("Custom")]
        [DefaultValue("False")]
        [Localizable(true)]
        public string IsReadOnly
        {
            get
            {
                string s = ViewState["IsReadOnly"] as string;
                return s == null ? String.Empty : s;
            }
            set
            {
                ViewState["IsReadOnly"] = value;
            }
        }
        
        protected static readonly object EventCommandObj = new object();

        public event CommandEventHandler Command
        {
            add
            {
                Events.AddHandler(EventCommandObj, value);
            }
            remove
            {
                Events.RemoveHandler(EventCommandObj, value);
            }
        }

        //this will raise the bubble event
        protected virtual void OnCommand(CommandEventArgs commandEventArgs)
        {
            CommandEventHandler eventHandler = (CommandEventHandler)Events[EventCommandObj];
            if (eventHandler != null)
            {
                eventHandler(this, commandEventArgs);
            }
            base.RaiseBubbleEvent(this, commandEventArgs);
        }

        //this overrides the OnTextChanged event on the normal textbox
        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);

            if (AutoPostBack)
            {
                //pass the event arguments to the OnCommand event to bubble up
                CommandEventArgs args = new CommandEventArgs(this.CommandName, this.CommandArgument);
                OnCommand(args);
            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            //if its readonly then render the text in a span tag
            if (IsReadOnly == "True")
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.Write(this.Text);
                writer.RenderEndTag();
            }
            else
            {
                //if not then render the textbox
                base.Render(writer);
            }
        }
    }
}

The Cake is a Lie

Now anytime you need to have the OnTextChanged event fire and bubble up within a Gridview than just use this control. It will also be very handy to do able to cause the textbox to become truely readonly.

 

kick it on DotNetKicks.com



Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading