Building Composite Controls in ASP.NET

A few weeks back I blogged about the new CompositeControl base class introduced with ASP.NET 2.0. 

Dino has just written an article on MSDN that does a good job of detailing it off more.  Click here to read it.  Definitely worth checking out if you are building your own server controls.

Hope this helps,

Scott

Published Tuesday, February 14, 2006 3:29 PM by ScottGu

Comments

# re: Building Composite Controls in ASP.NET

Tuesday, February 14, 2006 9:26 PM by Dave Reed
I always found it better to "delegate" properties through to the child controls rather than store them in my own ViewState key and then have to worry about copying it over at some point. For example instead of something like this:

public string Text
{
get { return ViewState["Text"] as string; }
set { ViewState["Text"] = value; }
}
public void CreateControlHierarchy()
{
TextBox tb = new TextBox();
tb.Text = this.Text;
}

I do it like this:

private TextBox txtFoo;
public MyControl()
{
this.EnsureChildControls();
}
public string Text
{
get { return this.txtFoo.Text; }
set { this.txtFoo.Text = value; }
}
protected override CreateChildControls()
{
this.txtFoo = new TextBox()
this.Controls.Add(txtFoo);
}

The reason I like this better is that the first way assumes no one is going to change the Text property after CreateChildControls occurs. If someone does, they will be dumb-founded as to why the control still renders its original value instead of what they changed it to. It also prevents accidentally bloating viewstate size. A lot of developers will set the inner controls state up in such a way that the values end up marked dirty in viewstate even though they're still the default values. Plus its so much cleaner.

It also allows me another trick... exposing the child controls themselves... so that users of my control can take advantage of all the features of that child control directly. For example if I were writing a Login Control and I wanted the user to be able to completely customize how the username and password textboxes behave, rather than surface Text, Style, MaxLength, TextBox, etc etc etc, I make 2 textbox properties (with only a 'get' accessor) that return the controls themselves. Now they can do what they want via:

<abc:MyControl UsernameTextBox-MaxLength=15 PasswordTextBox-MaxLength=20 />