自訂控件基類有三類:Control、WebControl、CompositeControl。後者封裝現有伺服器控件,靈活性高、復用性佳,且無需實作 IPostBackEventHandler、IPostBackDataHandler 等介面——子控件已內建支援。
構成元件:兩個 Label、兩個 TextBox、一個 Button。

public class Login : CompositeControl
{
private TextBox _userNameBox;
private TextBox _passwordBox;
private Button _submitButton;
protected override void CreateChildControls()
{
Controls.Clear();
_userNameBox = new TextBox { ID = "UserName" };
_passwordBox = new TextBox { ID = "Password", TextMode = TextMode.Password };
_submitButton = new Button { Text = "登入", ID = "Submit" };
_submitButton.Click += SubmitButton_Click;
Controls.Add(new Label { Text = "帳號:" });
Controls.Add(_userNameBox);
Controls.Add(new LiteralControl("<br/>"));
Controls.Add(new Label { Text = "密碼:" });
Controls.Add(_passwordBox);
Controls.Add(new LiteralControl("<br/>"));
Controls.Add(_submitButton);
}
// 屬性包裝、事件冒泡等...
}
繼承 CompositeControl 自動處理 INamingContainer,確保子控件 ID 唯一。下篇將詳細講解事件冒泡。