Royi Namir
Royi Namir

Reputation: 148524

How can i catch onclick event of Dynamically loaded control?

I have a dropdownlist (on Page) which has OnSelectedIndexChange event thats Loads different Control (ascx) dynamically each time ( with LoadControl Command) - into the page.

Each Control Has a Button(runat=server) and TextBox(runat=server).

When i click on the button - i cant get into the Onclick function .

How can i get into the OnClick Function of the Ascx ?

I know that each SelectedIndexChange its makes postback - so i know i have to save something in the viewstate. but i dont know how to save it and later get the values eneterd on the TexstBox. ( of Each ascx)

Upvotes: 1

Views: 1136

Answers (1)

James Johnson
James Johnson

Reputation: 46047

You need to add an event handler to the user control, like this:

public event EventHandler ButtonClick;

And in the click event of the button:

protected void Button1_Click(object sender, EventArgs e)
{
    if (this.ButtonClick != null)
        this.ButtonClick(this, e);
}

Then, from the page, you can get the click event like this:

<UC:MyUserControl ID="UserControl1" runat="server" OnButtonClick="UserControl1_ButtonClick" ... />

protected void UserControl1_ButtonClick(object sender, EventArgs e)
{
   //Handle the click event here
}

If you're loading the controls dynamically, then you'll need to make sure the controls are rehydrated after postback, and emulate the code above by assinging the event handler through code:

MyUserControl ctrl = (MyUserControl)this.LoadControl("...");
ctrl.ButtonClick += new EventHandler(UserControl1_ButtonClick);

Upvotes: 1

Related Questions