SingingEels : Development Community & Resource

Login

Articles

  • ADO.NET (2)
  • ASP.NET (36)
  • Azure (0)
  • LINQ (5)
  • Security (2)
  • Silverlight (3)
  • SQL (7)
  • Standards (5)
  • WCF (2)

Syndication

  • Articles RSS
  • Blogs RSS

Contribute

  • Our Authors List
  • Member Sign-Up
  • Suggestions Box

Custom Controls And Control Builders

(Aug 24 2007 - 10:43:25 PM by Timothy Khouri) - [print article]

ASP.NET has a strong set of web controls that provide common functionality for web developers. But there are times when you need to build something custom for your specific web project. Or you may want to author some controls that you think everyone can use. This article will show how to make your own custom controls and utilize control builders.

It's important to remember that 'user controls' and 'custom controls' are not the same thing. A user control (which inherits from the UserControl object) basically allows you to put existing controls together on a 'mini-page', and then use that over and over again. A custom control (which inherits from Control or WebControl) is something you build from the ground up. You will handle initialization, viewstate functionality, rendering - all on your own.

That might sound scary at first, but it's really not. The difference between user controls and custom controls is much like the difference between an automatic transmition car versus a manual transmition. You gain a lot more control, power and fuel economy, but you have to know what you're doing.

We'll start out basic; creating our first "Hello World" custom control. Then we'll add our own custom properties and see how we can interact with them in an ASP.NET web application. From there we'll see how to tap into the compiler with our own control builders.

Getting Started

To start with, I'm going to make a very basic web site application using Visual Studio 2005. I'll include all of the source in a zip file at the end of the article so that you can see it in action for yourself. I *could* put my custom controls right inside of the "App_Code" folder, but I want to demonstrate how you can do this in a seperate project. So I'm going to also have a "class library" project (just makes a DLL) containing the custom controls. In fact, the website won't have any C# code in there at all.

In order for my web application to know how to use the custom controls in the seperate DLL, I'll have to add a reference to that class library project. I'm also going to tell my web app that I plan on using all of the custom controls in the "SingingEels.CustomControls" namespace in that project. So here is my entire web.config file for this web app.

<?xml version="1.0"?>
<configuration>
   <system.web>
       <pages>
           <controls>
               <add assembly="SingingEelsClassLibrary"
                        namespace="SingingEels.CustomControls"
                        tagPrefix="Eels" />
           </controls>
       </pages>
   </system.web>
</configuration>

Now, any time I type "<Eels:" in my web project, intellisense will automatically come up with all of the available custom controls in the SingingEels.CustomControls namespace in my class library.

A Basic Custom Control

Now, let's make the most basic custom control in the world. It's going to be a custom control that has only one purpose: to write out a few words to the browser. Here's the C# code:

using System.Web.UI;

namespace SingingEels.CustomControls
{
   public class BasicCustomControl : Control
   {
       protected override void Render(HtmlTextWriter writer)
       {
           writer.Write("Hello SingingEels!");
       }
   }
}

Now, in my ASP.NET web page, I'll put the following:

<Eels:BasicCustomControl runat="server" />

And the results are obvious:

A web page displaying the text 'Hello SingingEels!'

Making Custom Properties

The above control is pretty pointless, unless of course it is your desire to give a shout out to Eels all the time. Let's allow people to enter their own phrase, and we'll echo it back on the screen.

Here is our new custom control that has a property called "WhatToSay". Again, here is the C#, the ASP.NET code and a screen shot of the results:

public class LeggoMyEcho : Control
{
   private string _whatToSay;

   public string WhatToSay
   {
       get { return this._whatToSay; }
       set { this._whatToSay = value; }
   }

   protected override void Render(HtmlTextWriter writer)
   {
       writer.Write(this.WhatToSay);
   }
}
<Eels:LeggoMyEcho runat="server" WhatToSay="Hey, how's it going?" />
A web page displaying the text 'Hey, how's it going?'

Control Builders

Now we are going to create another class. This time it will have two properties: Name and DateOfBirth. However, we don't want people to be allowed to enter a date that is greater than today's date. So, we could put the validation right inside of "set" method for our property, but the problem there is that the method is only called at runtime. So even though Visual Studio says "Build succeeded", I still will get this error:

A web page with a runtime error

This means that the developer using your control won't know there is an error when he's compiling the code. So, we'll make a control builder that will validate the properties during the compilation of the control. Here's how it works:

// First of all, here is my property. I have put the validation
// right in there in the set accessor.

public DateTime DateOfBirth
{
   get
   {
       return this._dateOfBirth;
   }

   set
   {
       if (value.Date >= DateTime.Today)
       {
           throw new Exception("You must enter a date that is before today.");
       }

       this._dateOfBirth = value;
   }
}

Now, here is my control builder. All I'm going to do is to call the "BuildObject" method during the compilation process. This way, my set method will fire, and an error will be thrown (if someone tried to assign a date that was later than today's date).

public class MyControlBuilder : ControlBuilder
{
   public override void OnAppendToParentBuilder(ControlBuilder parentBuilder)
   {
       try
       {
           this.BuildObject();
       }
       catch (Exception ex)
       {
           throw new Exception(ex.InnerException.Message);
       }

       base.OnAppendToParentBuilder(parentBuilder);
   }
}

Conclusion

There is a lot more that can be said about custom controls. We could talk about control persistance, template controls, how to store and retrieve data using the control state and much more. For now, I encourage you to download the source code of this project and play around with things for yourself.

Here is the full source: SingingEels_CustomControls.zip

You must be logged in to add comments. If you have not already done so, you can create an account here. If you already are a member, you first need to login before you can comment.

Developer / Architect / Author

Check Out Dev++

Test your development skills, give proof to recruiters and employers at dev++

Related Blogs

These are the most recent blog posts related to this article.

  • Aspose.Newsletter February 2012 Edition is out Now
  • Embed Videos inside PowerPoint Presentation & Stable PDF Generation
  • Excel to PDF Conversion, XLS, XLSX & ODS Rendering are Improved
  • Convert SVG to Pdf & Render Pdf into Image with Desired Dimensions
  • Add Optical Character Recognition in Java Web & Desktop Applications

Related Ads

SingingEels.com as of Feb 04 2012 - 12:39:46 AM - (0.0937524)