EventHandler is null
Asked Answered
C

3

9

I am trying to raise a click event from User control and handle it on the containing page. The problem I have is, when I click the button 'imgstep1' on the user control, the code behind imgstep1_click event triggers and but the 'btnHandler' event is alway null. Hence it doesnt call the parent event.

Any help on this will be much appreciated.

My User Control Code is :

.ascx code:

<asp:ImageButton ImageUrl="./images/step1.gif" 
        ID="imgstep1" runat="server" 
         OnClick="imgstep1_Click"/>

.ascx.cs code :

    public delegate void OnImageButtonClick();
    public event OnImageButtonClick btnHandler;

    protected void imgstep1_Click(object sender, ImageClickEventArgs e)
    {
        if (btnHandler != null)
            btnHandler();
    }

.aspx page code:

protected void Page_Load(object sender, EventArgs e)
{
     ucStepHdr.btnHandler += new StepsHeader.OnImageButtonClick(ucStepHdr_btnHandler);
}

void ucStepHdr_btnHandler()
{
  Response.Write ('test');
}
Chilly answered 11/9, 2009 at 12:4 Comment(1)
Is this the entire code, or is that "+= new ..." line inside a typical "if reload" type of block?Bastard
G
11

The code looks simple enough to work correctly. The only reason that btnHandler is null could be because the event registration code in the aspx page is not called.

Is there a post back ? Are you sure you are adding the event EACH TIME the page loads ???

ucStepHdr.btnHandler += new StepsHeader.OnImageButtonClick(ucStepHdr_btnHandler);
Gershon answered 11/9, 2009 at 12:21 Comment(1)
Yes! that was the problem. I was calling it witin (!IsPostBack) code. Once I put the code outside it started working. Thanks guys for all your answers.Chilly
F
1

If you remove OnClick="imgstep1_Click" and you put this in your ascx.cs

protected ImageButton imgstep1;

protected override void OnInit(EventArgs e)
{
    this.imgstep1.Click += new ImageClickEventHandler(imgstep1_Click);
}

Does this method of wiring up your event work?

Fox answered 11/9, 2009 at 12:38 Comment(0)
E
0

It looks like it should work... can you step through the code in the debugger, and see what the value of ucStepHdr.btnHandler is as soon as you set it in Page_Load? (Just an aside, traditionally these are set in init rather than load, but this isn't your issue.)

Escapee answered 11/9, 2009 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.