0
votes

I'm creating X linkbuttons in code behind using the following code:

HTML:

<div runat="server" id="div_tables">

</div>               

Backend:

LinkButton lnkB = new LinkButton();
lnkB.ID ="LB" + row.ItemArray[1].ToString() + row.ItemArray[2].ToString();
lnkB.Text = "Link to episode";
lnkB.Attributes.Add("runat", "server");
lnkB.Click += new EventHandler(lb_Clicked);
div_tables.Controls.Add(lnkB);   

OnClick method:

protected void lb_Clicked(object sender, EventArgs e)
{
  LinkButton b = sender as LinkButton;
  b.Text = "ASD";
}

On linkbutton click the entire page reloads instead of only the lb_Clicked method. I'm sure this is a basic linkbutton question, but I really hope someone can help me. Thank you in advance

#

EDIT, Found this other post which gives a solution to the problem: Can't call Click Event on dynamic button

As Mark correctly says, the data is lost at the pageload. This post suggest to use viewstate to only recreate the desired button.

1

1 Answers

0
votes

The entire page will always reload. Keep in mind, after the page is served there is no page anymore. When you click a button it then transmits everything back to the server. The server then spins up the page, goes through it's events, and then processes the appropriate postback such as the linkbutton's click event.

If you want to ensure certain other code isn't run, such as code in your OnLoad, you must enclose it in an if statement such as:

if(!Page.IsPostBack)
{
   // only do things the first time the page is laoded.
}

Also, when creating dynamic controls you have to re-create them each time the page posts back, and early enough in the page's lifecycle that they actually exist in time to receive a postback event. OnLoad or OnPreLoad are the latest events you should do this in (don't use Page_Load as it occurs after OnLoad and is generally too late).

For easier processing, such as if you are having the linkbutton do something with a record, you may want to look at the Command Event. This behaves as the click does, but gives you access to the CommandName and CommendArgument which you can set on the linkbutton and use to pass information such as the ID of a selected record.