Click-Event by dynamical Button

  • Thread starter Thread starter Liqun Xu
  • Start date Start date
L

Liqun Xu

Hallo NG,

I created a Button with Click-Event dynamically:
System.Web.UI.WebControls.Button bt_1 = new Button();
bt_1.Click += new EventHandler(bt_1_click);

and I implemented the Funktion bt_1_click in which I created a second
Button dynamically too.

System.Web.UI.WebControls.Button bt_2= new Button();
bt_2.Click += new EventHandler(bt_2_click);

The two Buttons display themselves well.
But the Funktion bt_2_click would never be fired.
I can not understand it. I used the same mechanism, but why the first Button
worked while the second one not.

Thanks a lot

Liqun
 
Liqun,

For an event to fire on postback the object that triggers the event has to
first be recreated.

Here's what's happening.

You are creating Button1 every time your page is loaded. This is fine
because when you click the button the page is reloaded. The button is
recreated and the click event is fired showing Button2.

But when you click Button2, the page is reloaded, Button1 is recreated but
Button1 wasn't clicked this time so Button2 is not recreated. If Button2
isn't recreated then it's event will never fire.

In this case what you'd have to do is put Button2's creation code into a
subroutine.

'Add a view state variable to the subroutine like this:
ViewState("CreateButton2") = True

'Inside of the Button1 click event call The code to create Button2.

'Also add an if then to your page load routine:

Dim CreateButton2 As Boolean = CType(ViewState("CreateButton2"), Boolean)
If CreateButton2 Then
'---Call Button2 Creation Subroutine here
End If

Now after you create Button2 the first time by clicking Button1 it will be
recreated from then on and your event will fire if it's clicked.


--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

Free code library at:
www.aboutfortunate.com

"Out of chaos comes order."
Nietzche
 
Dynamic controls must be re-created before their events can be fired.

As the second button is created and wired up in the bt_1_click postback
event of the first button, its onClick will never fire, because when the
page postback occures for the bt_2_click, bt_1_click is not fired, and
therefore the second button is not created, causing the event to be ignored.

Aren't you better off creating both buttons together, and changing the
Visible property instead?

Mun
 
Back
Top