Dynamically loaded control - how can I access a value in Page_Init

Posted by Sam on Stack Overflow See other posts from Stack Overflow or by Sam
Published on 2009-03-29T15:21:20Z Indexed on 2010/04/08 0:13 UTC
Read the original article Hit count: 638

Filed under:
|
|

I am loading a LinkButton dynamically when a user clicks on another LinkButton. I am attaching an event handler to it. When the user clicks on the dynamically loaded LinkButton, the event does not fire.

From what I've been reading, I understand this is because when the page posts back the dynamically loaded control no longer exists. It looks like I'm supposed to make sure this control is recreated in Page_Init.

The dynamically created LinkButton is dependedent on a value (Product ID). I need someway to access this value so I can properly create the control. ViewState is not accessible and I'm concerned if I use Session it could time out and then that wouldn't help. Any ideas?

Also, I hardcoded a Product ID value just for testing, and that still did not cause the event to fire. Is there something else I need to do?

protected void Page_Init(object sender, EventArgs e)
{
   SetTabText(1, 1);
}

SetTabText calls SetActionLinks which creates the LinkButton:

protected Panel SetActionLinks(int prodID, int tabID) {
...
LinkButton lnkBtn = new LinkButton();
lnkBtn.ID = "lnkBtn" + rand.Next().ToString();
lnkBtn.CommandName = "action";
lnkBtn.Command += new CommandEventHandler(this.lnkAction_Command);
panel.Controls.Add(lnkBtn);
...
}
void lnkAction_Command(object sender, CommandEventArgs e)
{
   LinkButton btn = (LinkButton)sender;
   switch (btn.CommandArgument)
   {
      AddCart();
   }
}

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about controls