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

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

From what I read, I understand this because when the page returns, the dynamically loaded control no longer exists. Looks like I have to make sure this control is recreated in Page_Init.

Dynamically created LinkButton depends on the value (product identifier). I need to somehow access this value so that I can correctly create the control. ViewState is unavailable and I am worried that I am using Session, this may lead to a timeout, and then it will not help. Any ideas?

In addition, I hard-coded the value of the product identifier for testing only, and this still did not raise the event. Is there anything else I need to do?

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

SetTabText calls SetActionLinks, which creates a 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();
   }
}
+3
source share
6 answers

You can put your product identifier in a hidden field and get its value in Page_Init using

Page.Request(Page.FindControl("hdnPageIdField"))

, ViewState SessionState

greate arcticle

+5

, :

lnkBtn.ID = "lnkBtn" + rand.Next().ToString();

id, postbacks.

ViewState Page_Load. , ViewState

+2

, - . , , ASP.NET , ping-ponging viewstate .

, PageInit , ( ). , , , , . ( , ..).

ASP.NET(http://msdn.microsoft.com/en-us/library/ms178472.aspx).

+1
source

This works in Page_Init

HiddenField ctrl = (HiddenField)Page.FindControl("hfTest");
string strValue = Page.Request.Form.Get(ctrl.ClientID);

The controls that will be loaded in the HiddenField will be stored (pipe restriction), and we can dynamically load the controls.

+1
source

Look at anonymous delegates

LinkButton lb = new LinkButton();
lb.Command += delegate { // do something here. also you can access any variable from current stack };
0
source

Do you have AutoEventWireup="true"in your .aspx file?

0
source

Source: https://habr.com/ru/post/1705535/


All Articles