Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

If have found a piece of code that allows you to create own events on a usercontrol. Great! But it doesn't work with me. This is the (changed to my situation) code:

Usercontrol:
C#
public partial class Usercontrols_Modal : System.Web.UI.UserControl
{
    public delegate void ResultCompletedEventHandler(object sender, ReturnResultArgs e);
    public event ResultCompletedEventHandler ReturnResult;

    protected void btnYes_Click(object sender, EventArgs e)
    {
        ReturnResultArgs args = new ReturnResultArgs();
        args.Result = true;
        this.ReturnResult(this, args);
    }
}

public class ReturnResultArgs : EventArgs
{
    // this is a string value I will set using a dropdownlist
    public Boolean Result { get; set; }
}


On the webform (code behind):

C#
public void AskQuestion(object sender, EventArgs e)
{
    modaldelete.ReturnResult +=new Usercontrols_Modal.ResultCompletedEventHandler(modaldelete_ReturnResult);
    //modaldelete.SearchCompleted +=new Usercontrols_Modal.SearchCompletedEventHandler(modaldelete_SearchCompleted);
    modaldelete.Visible = true;
}

protected void modaldelete_ReturnResult(object sender, ReturnResultArgs e)
{
    Response.Redirect("/default.aspx");
}


My code breaks on this.ReturnResult(this, args);. It seems ReturnResult is null and cannot continue.

What am I doing wrong??

Thanks in advance
Posted
Updated 4-Sep-11 2:04am
v2

1 solution

Always check that the event has subscribers before firing it:
C#
if (this.ReturnResult != null) {
        ReturnResultArgs args = new ReturnResultArgs();
        args.Result = true;
        this.ReturnResult(this, args);
}

If btnYes_Click is executed before the event is subscribed in AskQuestion, then you would get the error mentioned.
 
Share this answer
 
Comments
Ken Elz 4-Sep-11 8:13am    
Okay, cool (added to my script)... But this.ReturnResult is always null in my case, so it will never be fired. How can I make it.... not null?
Wendelius 4-Sep-11 9:30am    
Is the AskQuestion method executed? That's where you wire the event so it should be executed in order to receive the event (and the event to be non-null).
Ken Elz 4-Sep-11 10:19am    
You made me think of something... What if the modaldelete.ReturnResult += new Usercontrols_Modal.ResultCompletedEventHandler(modaldelete_ReturnResult); is in the wrong position? So I put that line in the Page_Load... And it works!
A little bit of a noob action of me, but I'm not perfect ;)

Thanks for you're help
Wendelius 4-Sep-11 10:30am    
Glad it helped :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900