Problems of this kind are almost always a result of wiring up the event handlers in the wrong place in the page lifecycle.
OnInit happens before LoadPostData is called, and this is the reason it appears to work on the second click. What's actually happening is that you are handling an event from a previous postback.
- Page_Init
- LoadViewState
- LoadPostData
- Page_Load
- RaisePostDataChangedEvent
- RaisePostBackEvent
- Page_PreRender
- SaveViewState
- Page_Render
- Page_UnLoad
This is a simplified version of events from Asp.net 1.1; 2.0 has some extra events inserted inbetween, like OnPreInit. The order remains though.
You must use an event from Load or later. Some people choose PreRender, but convention for DataBinding is in Load.
UPDATE
I see you are dynamically adding controls to the controls tree. This is fraught with pitfalls (but is perfectly workable.)
a) ensure you add the dynamic controls EVERY time the page loads, not just on postback. Postback/viewstate persists STATE (i.e. data), not objects. You should add them in OnInit (OnLoad works too, but it is more troublesome to maintain). You are currently only adding on postback, this is why the 2nd postback works (and not the first)
b) only initialize the dynamic controls ONCE, like you would any other control - on [!IsPostBack], in Load.
-Oisin
Hi all!
Thank everbody for helping me out. I found the solution:
I didn't know that the dynamically created button needs a ID value. I suggested that Asp know wich button is created. Unfortunately i was wrong. It seems that .NET compares the ID on the buttons and not the position in ControlTree.
I added
new Button{ID = itr.ToString()}
Now when server rebuilds the site, eventhandler are hitted.
regards x.
I just had a similar problem. I tried lots of solutions, but in the end I noticed that one of the textboxes on my webform was posting back to the server, which messed things up. It was a hard bug to catch because I didn't mean to have my textbox do that.