ashkufaraz
ashkufaraz

Reputation: 5297

add new event to button

protected void Page_Load(object sender, EventArgs e)
{
        Button a = new Button();
        a.Width = 100;
        a.Height = 100;
        a.Text = "one";
        a.Click += new EventHandler(test);
        form1.Controls.Add(a);        
}

protected void test(object sender, EventArgs e)
{
    Button b = new Button();
    b.Width = 100;
    b.Height = 100;
    b.Text = "two";
    b.Click += new EventHandler(test2);
    form1.Controls.Add(b );
    Response.Write("aaaaaaaaaaaaaaaaaa");
}


protected void test2(object sender, EventArgs e)
{
    Response.Write("bbbbbbbbbbbbbbb");
}

when click on one show Button two but when click on twobutton does not run test2???? when click on two page refresh.

i want first click on 'one' and then 'two' show the button only after button a has been clicked

Upvotes: 1

Views: 13396

Answers (3)

treetey
treetey

Reputation: 829

Try this:

protected void Page_Init(object sender, EventArgs e)
{
    Button a = new Button();
    a.Width = 100;
    a.Height = 100;
    a.Text = "one";
    a.Click += new EventHandler(test);
    form1.Controls.Add(a);

    Button b = new Button();
    b.Visible = false;
    b.Width = 100;
    b.Height = 100;
    b.Text = "two";
    b.Click += new EventHandler(test2);
    form1.Controls.Add(b);
}

protected void test(object sender, EventArgs e)
{
    b.Visible = true;
    Response.Write("aaaaaaaaaaaaaaaaaa");
}


protected void test2(object sender, EventArgs e)
{
    Response.Write("bbbbbbbbbbbbbbb");
}

Upvotes: 3

Heinzi
Heinzi

Reputation: 172200

You have to recreate dynamic controls (such as your new button b) and associate their event handlers again on each postback. Thus, you need to move the code from test to Page_Load. If you want to show the button only after button a has been clicked, either make button b invisible (simple solution) or store some Boolean in the viewstate that triggers creation of b (more complicated solution).

Upvotes: 2

Anders Abel
Anders Abel

Reputation: 69250

Each time an ASP page is accessed (or refreshed), the object is recreated and the Page_Load event is run. This means that when you hit the first button, the second is created and the event is subscribed to in that instance of the page object.

When you hit the button the next time, a new page object is created and in that page object the event has never been subscribed to.

Creating controls dynamically is often a bad idea, instead create all controls and hide those that you don't want to display right away. Also you should add a check for IsPostBack in your page load, so that you can differentiate between first-time initialization and when the object is recreated on postback.

Upvotes: 1

Related Questions