Click-Event by dynamical Button

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
 
S

S. Justin Gengo

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
 
M

Munsifali Rashid

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top