Help: EventHandlers???

liunx

Guest
Hi,
I am developing in ASP.NET using C#. I am in a situation where I have to create a button 'on the fly' when another button is clicked. I have attached the Click eventhandler to the second button button but it is not responding to it.how do I get around this. Here is a rough summary of my code:



public void createButton1(){
Button bt1 = new Button();
bt1.Text = "Button 1";
bt1.Click += new EventHandler(CreateButton2);
bt1.Visible = true;
}

private void CreateButton2(object sender, System.EventArgs e){
Button bt2 = new Button();
bt2.Text = "Button 2";
bt2.Click += new EventHandler(CreateButton3);
bt2.Visible = true;
}

private void CreateButton3(object sender, System.EventArgs e){
Button bt3 = new Button();
bt3.Text = "Button 3";
bt3.Visible = true;
}

Button 1 displays and when clicked on, 'Button 2' is displayed, but clicking on 'Button 2' does not lead to Button 3 to display!! Is it because 'Button 2's click handler (bt2.Click += new EventHandler(CreateButton3)) is defined inside another handler ( CreateButton2 )??? Please help.Dynamic controls have to be recreated during each postback in order to use events, for example you can create booleans for each of your buttons (btn1,btn2,btn3) and store them in session state or viewstate. During each postback call the same method and within that method, if btn1 = true then create button 1, if btn2 = true then create button 2, if btn3 = true then create button 3. Example psuedo code, good luck;


public sub page_load(args)
CreateButtons()
end sub

public sub CreateButtons()
'stuff to create button1

if session.item("btn2") then
'stuff to create button2
end if

if session.item("btn3") then
'stuff to create button3
end if
end sub

public sub btn1_click(byval sender as object, byval e as eventargs)
session.item("btn2") = true
dim btn2 as new button
'btn id, event hookup, etc.
mycontrol.controls.add(btn2)
end sub
public sub btn2_click(byval sender as object, byval e as eventargs)
session.item("btn3") = true
dim btn3 as new button
'btn id, event hookup, etc.
mycontrol.controls.add(btn3)
end sub
public sub btn3_click(byval sender as object, byval e as eventargs)
'whatever you do here.
end sub
 
Back
Top