开发者

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

开发者 https://www.devze.com 2023-02-13 16:42 出处:网络
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:

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 But开发者_运维知识库ton 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消