简体   繁体   中英

How to handle the Click event of a button in a custom ITemplate control?

I've created a custom control in ASP.NET for showing a pop-up message box. In my MessageBox class, I have a Content property as ITemplate like the following:

[PersistenceMode(PersistenceMode.InnerProperty)]
    [TemplateContainer(typeof(MessageBoxContent))]
    [TemplateInstance(TemplateInstance.Single)]
    public ITemplate Content { get; set; }

I used my custom control in my page like this:

<cc1:MessageBox ID="MessageBox1" runat="server">
    <Content>
        <asp:Button Text="Save" runat="server" ID="B_Save" />
    </Content>
</cc1:MessageBox>

Even I set the the Content property's TemplateInstance to Single, I still can't have access to the Button control.

All I want to do is to handle the click event of the button. When I assign an event handler to the button control and run the project, it throws a NullReferenceException. Is there a way to handle this issue?

I had a similar problem in a custom control I created.

I wanted to find a LinkButton within the Itemplate Template property and assign a Click Event to it.

I was instantiating the template in OnInit and assigning the click event in OnLoad .

I found the LinkButton in OnLoad , no problem. I was also able to add the Click event which all seemed fine until, when I tried to click the LinkButton, the Click event was not firing.

The fix for me was to make my custom control implement INamingContainer .

It depends on when you're calling the template instantiation.

You shold be doing that during container's Load event, and you'll get access to template-injected controls just after calling ITemplate.InstantiateIn method.

If you don't have access to the control, it should be you're looking in a wrong control hierarchy level. Maybe you're nesting it in the wrong place?

Can you give us a part of your source code? It could be good to see where you instantiate your control template and later, where you try to add a Click event handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM