asp.netmaskededitextender

How to create a MaskedEditExtender on the fly?


I want to create a number of masked edit extenders from codebehind. Something like:

private MaskedEditExtender m_maskedEditExtender;
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    m_maskedEditExtender = new MaskedEditExtender()
    {
        BehaviorID = "clientName"
    };
    m_maskedEditExtender.Mask = "999999999";
    this.Controls.Add(m_maskedEditExtender);
}
protected override void Render(HtmlTextWriter writer)
{
    m_maskedEditExtender.RenderControl(writer);
}

When I do this, I get a NullReferenceException on OnLoad of MaskedEditExtender. What is the correct way of doing that? Please note that putting the extender into a repeater-like control and using DataBind does not work for me.

Edit: I do not have an update panel. Turns out I also need to specify a target control on serverside.


Solution

  • See ASP.NET Page Life Cycle Overview if this is in a Page subclass. If you scroll down to the event list, that page advises you to use the PreInit event to create any dynamic controls. It's necessary to do that early to ensure that ASP.NET cleanly loads ViewState at the right stage, among other things.

    If you are doing this in a web user control or custom control, though, override CreateChildControls and do this in there.

    Post a more complete code example if that doesn't help.