Click here to Skip to main content
13,297,321 members (70,301 online)
Click here to Skip to main content
Add your own
alternative version


38 bookmarked
Posted 4 May 2006

WYSIWYG For Custom Web Controls

, 4 May 2006
Rate this:
Please Sign up or sign in to vote.
Design graphical layout of Custom Controls using standard tools available with the Visual Studio IDE.

Sample Image - ConvertUserToCustom.jpg


This article describes a control engineering technique that allows developers to design graphical layouts of Custom Controls using standard tools available with the Visual Studio IDE, aiming to avoid tedious hand-coding of control hierarchies.


Decisions made during construction phase of a complex project are not always unambiguous. Compromises are made in order to prove concepts, meet the deadlines, or to enforce standards. With time, these compromises begin to accumulate into significant “design debt”, which, when left unattended, incurs interest at a fantastic rate. Refactoring coupled with Test-Driven Development is probably the most reliable approach to keep both the design debt and the resulting system entropy in check.

With ASP.NET web projects specifically, it is very common to see an attempt to re-use class libraries of the pre-existing sites, copying the markup into a new project, and slightly modifying the code-behind directives. Consequently, an ‘internal’ user control built exclusively for one project, all of a sudden, can become a required part of multiple new front-ends. User Controls being a compromise in and out of itself are reusable, however, thanks to their limitations fall far behind the more dynamic and “professional” Custom Controls. What if it would be a matter of a few easy steps to turn an ungainly User Control into its sleek and easy to deploy ‘Custom’ variety? This article will illustrate an approach suitable for converting User Controls into Custom Controls while preserving the original work and functionality. The author fully understands, however, that significant positive effect from this approach can also be realized when developing new composite Custom Controls from scratch. The two preceding paragraphs simply provided the historical background for the readers as well as an excuse for this creative carping exercise.

More on User Controls vs. Custom Controls

“User” controls (in concept) are considered to be easier to work with than “Custom” controls simply because the design-time capabilities of Visual Studio make UI building process straightforward and fast. There is no need to hand-code control positioning and behavior as with the Custom Controls. If there is a requirement for a simple reusable element of the user interface that will not be inherited and exposed only to the project where it resides, the choice in favor of the User Controls is obvious.

However, an attempt to take a User Control to its next level of abstraction or to deploy it outside of the hosting project is somewhat akin to commuting to work by means of a John Deere lawnmower – absolutely feasible and very cool, but hardly practical. This is where the Custom Controls start to prove their worth. They can be effectively inherited, and have a lightweight deployment footprint/overhead. Now, is it possible to combine the WYSIWYG design capability of a User Control with a Custom Control and shamelessly exploit advantages offered by both technologies? In this article, we will attempt to do just that.

The Sample Solution

I have included both the control project (ControlTestRange - class library) and the web project (ControlTester - web project) for testing the control in the sample code. Both are built with Visual Studio 2005. The solution file is solution\Projects\ControlTestRange\ControlTestRange.sln.

I have not tried this with VS2003/.NET 1.1 yet. but there are reasons to believe that it will work just as well.

Step 1 - Designing the User Interface

We will start by designing UI for the sample control. The idea is to keep it as simple and as useless as possible to prevent people from trying to plug it into their real-life projects. After all. it’s just an illustration of the technique. and not an Open Source product. For starters, I added a new HTML page to the control project and replaced the entire HTML generated by the template with short but very meaningful notation:

Then, I renamed the HTM file into a “controlMarkup.ascx” in the secret hope that the IDE will let it have the same design-time capabilities as a ‘normal’ User Control (I was quite shocked when it did). Here is the result in both the HTML and the Design renditions:

Control mark-up

There are two controls on this ‘phantom’ ASCX template – one is a server-side drop-down list, and another is a basic HTML button. The button is provided with an even more basic event handler.

Step 2 – Adding the Control Class

I am not extremely good with names, so my test control is uncomplicatedly enough called TestControl. I added it to the control project, and made it derive from the Control class. You can also derive from the CompositeControl class because it (in the characteristically precise and laconic MSDN-speak) “Implements the basic functionality required by Web controls that contain child controls”.

Step 3- Embedded Resource

To simplify deployment of a server control, we are interested in the smallest possible number of deployment units. Ideally, there should be just one – the assembly that hosts our world-greatest control library. Adding the markup file as Embedded Resource, our project solves this task very nicely. In the control project, the Build Action property on the “controlMarkup.ascx” file is set to “Embedded Resource”.

Embedded Resource

To retrieve this resource, I created a short helper method GetResource:

private string GetResource(string resourceName)
    Stream stream = 
      GetType(), resourceName);
    using (StreamReader reader = new StreamReader(stream))
        return reader.ReadToEnd();

It is being used to get the content of the controlMarkup.ascx:

string content = GetResource("controlMarkup.ascx");

You can find out more about Embedded Resources on MSDN. It’s really fascinating, especially since ASP.NET 2.0 is not entirely ignorant of this capability and offers a new and exciting feature affectionately called WebResource (a nice overview by Gary Dryden is available here).

Step 4 - Wiring the Control

We discovered earlier how easy it is to mine embedded resources from the dark depths of an assembly. Now, putting this knowledge to good use, we are going to override the OnLoad method of the base class.

protected override void OnLoad(EventArgs e)
    if (DesignMode) return;
    string content = GetResource("controlMarkup.ascx");
    Control control = Page.ParseControl(content);
    m_Ddl = control.FindControl("ddlTrigger") as DropDownList;
    m_Ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);

After the markup from the embedded controlMarkup.ascx is loaded into a string variable, the magic ParseControl method exposed by the hosting page translates it into an instance of a Control. It is Officially Alive! The next move is to add the monster to the TestControl itself. An important part of this exercise was to make sure that server controls are fully functional in this environment. The instance-level field m_Ddl is assigned a reference to a member of Frankenstein’s Controls collection (we know this will work for fact since we actually built the monster). An event handler is then assigned to the drop-down list’s SelectedIndexChanged event. The code in the handler changes the background color of the dropdown list to create a little dramatic effect:

void ddl_SelectedIndexChanged(object sender, EventArgs e)
    m_Ddl.BackColor = 

A strangely normal behavior is observed when running the solution. The event handlers, both client- and server-side, are responding properly, and the inner state of the control is preserved (the background color of the dropdown actually changes). Needless to say, the client-side “onclick” handler also fires as ordered:

End result

Step 5 – FFFFFF (Fat-Free-Food-For-Farther-‘Fot’) and The Conclusion

In most cases, it is significantly less taxing to code the appearance of a control in HTML versus C# or VB. The approach demonstrated here is based, in general, on the ParseControl method of the System.UI.Web.Page class. It is natural to expect the tag prefixes registered on the hosting page to be recognized by the ParseControl. This means that third-party controls can be added to the ‘Frankenstein’, if necessary, provided that the page itself is aware of their existence.

I leave it to the reader to explore more advanced aspects of this technique: ViewState management, subclassing, or hosting it in Master Pages, just to name a few. Please feel free to share what you were able to discover and, as always, Happy Coding!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Alex Soldatov
United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralWYSIWYG For Custom Web Controls Pin
wking-farlow10-Dec-08 4:06
memberwking-farlow10-Dec-08 4:06 
GeneralResource Issue Pin
torr010115-Jul-07 7:12
membertorr010115-Jul-07 7:12 
GeneralThis is a great technique Pin
bjd4jc18-May-07 10:47
memberbjd4jc18-May-07 10:47 
QuestionCool Great IDEA but one Q though... Pin
stixoffire23-Mar-07 12:02
memberstixoffire23-Mar-07 12:02 
GeneralDesign rendering Pin
Fede Gamon24-Oct-06 6:57
memberFede Gamon24-Oct-06 6:57 
AnswerRe: Design rendering Pin
stixoffire20-Apr-08 19:59
memberstixoffire20-Apr-08 19:59 
Perhaps you need the object defined -
createchild controls
// this is called from the base.render method
protected override void CreateChildControls()
Controls.Add(the Server Control)

You might be able to use EnsureChildControls - ...IDK

You are going in the direction I am planning to take..
QuestionProblem when adding the control multiple times in the same page Pin
jlecain30-Aug-06 4:37
memberjlecain30-Aug-06 4:37 
AnswerRe: Problem when adding the control multiple times in the same page Pin
Alex Soldatov30-Aug-06 11:47
memberAlex Soldatov30-Aug-06 11:47 
GeneralVery nice, but... :-) Pin
kpronk7016-May-06 7:06
memberkpronk7016-May-06 7:06 
GeneralRe: Very nice, but... :-) Pin
Alex Soldatov16-May-06 15:29
memberAlex Soldatov16-May-06 15:29 
GeneralRe: Very nice, but... :-) Pin
kpronk7017-May-06 9:01
memberkpronk7017-May-06 9:01 
GeneralRe: Very nice, but... :-) Pin
Alex Soldatov17-May-06 11:38
memberAlex Soldatov17-May-06 11:38 
GeneralRe: Very nice, but... :-) Pin
kpronk7018-May-06 8:11
memberkpronk7018-May-06 8:11 
GeneralWeb Application Project Pin
Michael Freidgeim11-Jul-06 15:56
memberMichael Freidgeim11-Jul-06 15:56 
GeneralRe: Web Application Project Pin
Alex Soldatov12-Jul-06 5:37
memberAlex Soldatov12-Jul-06 5:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171207.1 | Last Updated 4 May 2006
Article Copyright 2006 by Alex Soldatov
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid