Handling dynamically added UserControl's buttons

39 views Asked by At

In my ASP.Net page, I have a PlaceHolder in which I add an undetermined amount of UserControls based on my database. These UserControls are added thanks to the user's click of a button, not in any Page_Load or Page_Init event.

Each UserControl added into the PlaceHolder has multiple buttons, with various behaviors.

Problem : When the user clicks on one of the many UsersControls' buttons, the events tied to the buttons in the UserControls are not fired : Only the MainPage Page_Load event is fired which resets the whole page (and clears the PlaceHolder).

ASPX page :

<asp:PlaceHolder ID="PlaceHolder1" runat="server" />  

ASPX code_behind :

protected void Btn_Click(object sender, EventArgs e)
{
   // get data from database and populate myListString
   foreach (string data in myListString)
   {  
      UserControl Tab = (UserControl)LoadControl("~/UserControl1.ascx");
      PlaceHolder1.Controls.Add(Tab);
   }
}

UserControl page :

<asp:ImageButton ID="Btn_Update1" runat="server" ImageUrl="~/Images/Save.png" OnClick="Btn_Update1_Click" />

UserControl code_behind :

protected void Btn_Update1_Click(object sender, ImageClickEventArgs e)
{
   // Update the database
   // Update the UserControl
   // BUT event is never fired because ASPX page's Page_Load event is fired istead
}

I've browsed dozens of threads on the matter, and nothing helped me. I understand that dynamically added controls must be instantiated and initialized on each postback, but isn't the sole purpose of UpdatePanels to do partial postbacks on specified portions of the page ?

Maybe I could use Session to store all the UserControls data and user input, and reload everything after every user's click on a UserControl button, but honestly that looks like a lot of work for something quite small... Any thought please ? :)

What I'd like to do, is adding UserControls to my PlaceHolder on the user's button click, and being able to access each UserControl's buttons events. When the user clicks on said buttons, the whole page doesn't need to load again, only the specific UserControl I want to update.

0

There are 0 answers