Lessons in this course (9)

3. Composite controls, events, postback data and templates

IntermediateMediumLesson 3 of 9
csharp
// Composite control: label + textbox + validator + event
public class SearchBox : CompositeControl, INamingContainer
{
    private TextBox _text = null!;
    private Button _button = null!;
    public event EventHandler<string>? Search;              // expose an event to the page

    public string Placeholder { get => (string?)ViewState["Ph"] ?? "Search"; set => ViewState["Ph"] = value; }

    protected override void CreateChildControls()          // create children on every request (postbacks too)
    {
        Controls.Clear();
        _text = new TextBox { ID = "q" };
        _text.Attributes["placeholder"] = Placeholder;
        _button = new Button { ID = "go", Text = "Go" };
        _button.Click += (s, e) => Search?.Invoke(this, _text.Text.Trim());
        Controls.Add(_text);
        Controls.Add(_button);
    }
}
  • INamingContainer gives child controls unique client ids (SearchBox1$q).
  • IPostBackDataHandler — implement LoadPostData/RaisePostDataChangedEvent for controls that read posted form values themselves.
  • IPostBackEventHandler — RaisePostBackEvent for controls that trigger postbacks (Page.ClientScript.GetPostBackEventReference).
  • Templated controls — [TemplateContainer] + ITemplate properties (ItemTemplate, EmptyTemplate) let users supply markup, like Repeater.
  • ControlState (OnInit: Page.RegisterRequiresControlState(this), override SaveControlState/LoadControlState) for state that must work even with ViewState disabled.
  • Embedded resources (JS/CSS/images) via [assembly: WebResource] and ClientScript.GetWebResourceUrl.