Search code examples
c#asp.net.netevent-handlingcustom-events

Custom Event became null on 2nd call


I have written on event in a user control and that user control used twice in a page. Now the problem is, I am getting the Event as null for the 2nd time. Why? How to resolve the issue? Please help.

My code like:

in ascx:

public delegate void OnGoButtonClick();
public event OnGoButtonClick btnGoClickHandler;
protected void btnGo_Click(object sender, EventArgs e)
{
   if (btnGoClickHandler != null)
                btnGoClickHandler();
}

In aspx:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    MyUserControl.btnGoClickHandler += new UserControls.LoanPicker.OnGoButtonClick(PopulateDataOnGo);
}

But for the 2nd user control it is always null.


Solution

  • Make sure to subscribe to the event from both controls.

    Regarding your comment:

    how to detect which user control being triggered

    You need to supply the object that raised the event to the event handler. Start by altering the delegate signature to look like this:

    public delegate void OnGoButtonClick(object sender);
    public event OnGoButtonClick btnGoClickHandler;
    protected void btnGo_Click(object sender, EventArgs e)
    {
       if (btnGoClickHandler != null) 
           btnGoClickHandler(this);
    }
    

    Now alter the event handler which in this case appears to be PopulateDataOnGo to accept the sender and check who raised the event from there:

    public void PopulateDataOnGo(object sender)
    {
        if (sender is ControlType1)
        {
        } 
        else if (sender is ControlType2)
        {
        }
    }