When you dynamically generate a LinkButton in code that will be placed inside an UpdatePanel, you’ll experience that the Click event for the LinkButton results in a full postback in stead of the UpdatePanel being triggered. There’s a rather simpel solution to this problem…
First, let’s take a look at the scenario. Consider this HTML:
There’s a literal control outside of the UpdatePanel. There’s a second literal control inside the UpdatePanel. Besides that, there is a PlaceHolder inside the UpdatePanel, where the generated LinkButton will be placed. The parent control doesn’t have to be a PlaceHolder, it can also be a repeater or something like that.
Next, consider this code:
As you can see, a LinkButton is generated and added to the PlaceHolder in every PageLoad. In the same PageLoad, the literal outside of the UpdatePanel is updated. The literal inside the UpdatePanel is only updated when the LinkButton is clicked. This makes for something like this for the first time the page loads:
and something like this after the LinkButton is clicked:
Because the LinkButton is inside the UpdatePanel, you would think hitting it would trigger the UpdatePanel so only the literal control inside the UpdatePanel gets updated. The fact that the two literals have the same time on it in the ‘after LinkButton clicked’ image, shows that the entire page was posted back.
The problem here is in the fact that the ID for the LinkButton is not set in the code. Weird thing is that when you change the code to generate a normal ASP.NET Button (with or without an ID), the problem doesn’t occur. This has something to do with the fact that both the input rendered for the button and the link rendered for the linkbutton have no ID, but the input control does have a name that can be used to relate events/postbacks to. The link doesn’t have that either, so I’m guessing it has something to do with that.
So the solution is rather simple. Add a line in code where the ID for the control is set (like linkButton.ID = “TestLinkButton”;) After clicking the linkbutton in my example, only the literal in the UpdatePanel is updated. Hooray! 😉