I've seen a a lot of people posting questions these days about composite controls. Most are having problems with viewstate. I thought I'd write up a simple example composite control so I can point at it. So here it is, a simple composite control that has a label and a textbox.
// Composite controls should derive from WebControl and implement INamingContainer
public class FooControl : WebControl, INamingContainer {
// Override the getter for Controls with a call to EnsureChildControls.
// This makes sure that your child controls always exist when they need to.
public override ControlCollection Controls {
get {
EnsureChildControls();
return base.Controls;
}
}
// This is where you instantiate your child controls and set their default values.
protected override void CreateChildControls() {
Controls.Clear();
myLabel = new Label();
myLabel.ID = "myLabel";
Controls.Add( myLabel );
myTextBox = new TextBox();
myTextBox.ID = "myTextBox";
Controls.Add( myTextBox );
}
//These properties are delegated to the child controls.
// As such, we call EnsureChildControls to make sure they are instantiated before accessing them.
public String LabelText {
get {
EnsureChildControls();
return myLabel.Text;
}
set {
EnsureChildControls();
myLabel.Text = value;
}
}
public String TextBoxText {
get {
EnsureChildControls();
return myTextBox.Text;
}
set {
EnsureChildControls();
myTextBox.Text = value;
}
}
private Label myLabel;
private TextBox myTextBox;
}