So I have a weird situation here... I have an System.Web.UI.WebControls.WebParts.EditorPart class. It renders a "Search" button, when you click this button, it's clickHandler method does a DB search, and dynamically creates a LinkButton for each row it returns, sets the CommandName and CommandArgument properties and adds a CommandEventHandler method, then adds the LinkButton control to the page.
The problem is, when you click a LinkButton, its CommandEventHandler method is never called, it looks like the page just posts back to where it was before the ORIGINAL "Search" button was pressed.
I have seen postings saying that you need to add the event handlers in OnLoad() or some other early method, but my LinkButtons haven't even been created until the user tells us what to search for and hits the "Search" button... Any ideas on how to deal with this?
Thanks!
You need to re-add the dynamically created controls, in the onload, so that they can be in the page hierarchy and fire their event.
A dirty hack I just came up with, is to create dummy LinkButtons with the same IDs as the real buttons. So let's say you are going to create a LinkButton "foo" at Pre_Render (which is too late), then also create a dummy foo at Page_Load:
(Where "dummyButtons" is just a PlaceHolder on the page with Visibility set to false.) It's ugly, but it works.
This is my favorite trick :)
Our scenario is to first render a control. Then using some input from the user, render further controls and have them respond to events.
The key here is state - you need to know the state of the control when it arrives at PostBack - so we use ViewState. The issue becomes then a chicken-and-egg problem; ViewState isn't available until after the
LoadViewState()
call, but you must create the controls before that call to have the events fired correctly.The trick is to override
LoadViewState()
andSaveViewState()
so we can control things.(note that the code below is rough, from memory and probably has issues)