Thursday, June 23, 2011

How to add an event into user control in ASP.NET WebForms?


Reason: Put two user controls in same page, you want call one function in B while one thing happens in A.

Three steps to do that: Define, Raise and Book event. 

Define event in A:
    public delegate void AfterOneTask ();
    public event AfterOneTask AfterOneTaskHandler;

Raise event in A:
    protected void Submit_Click(object sender, EventArgs e)
    {
       ….
        if (this. AfterOneTaskHandler!= null) AfterOneTaskHandler();
       }
Book event in B:
    protected void Page_Init(object sender, EventArgs e)
    {
        this.ctlA.AfterOneTaskHandler +=new UserControlA.AfterOneTask(controlb.method1);
    }

No comments:

Post a Comment