views:

1661

answers:

2

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.

A: 

Your example is not providing a TargetControlID.

Do you have an updatePanel on the page? I had problems dynamically creating extenders as they weren't being added to the updatePanel content.

I also think you have to do somethin with the ScriptManager (registering the extender) but I could be mistaken (I don't have access to the code I did dynamic extenders at the moment).

Slace
+1  A: 

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.

Jesse Millikan