Loadcontrol event Is working but how?

367 Views Asked by At

Page Code :

public partial class Default2 : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        Uctest ctrl = (Uctest) this.LoadControl("Uctest.ascx");
        ctrl.ID = "aaa111";
        Page.Controls.Add(ctrl);
    }
}

Ascx Code :

public partial class Uctest : UserControl
{
    protected void btn1_Click(object sender, EventArgs e)
    {
    }
}

I have a page and ascx. the ascx contains asp:button and asp:textbox

My goal is to reach to the 'btn1_Click' event.

this is working. - when i press the button it goes to the event and its all ok.

but i cant understand why. because each postback it is RECREATING the CONTROL AGAIN , so how does he knows to attch the pressed event to the upcoming new created ascx (because of the postback) ??

1

There are 1 best solutions below

5
On BEST ANSWER

When you post back, you're re-creating the user control.

It is the user control that contains the event method and it is the user control that sets up the event delegation, so it makes sense that each time you create an instance of the user control, it also creates the event method and attaches to it.