views:

22

answers:

2

i careate button control and place in panel but not working?

protected void Button1_Click(object sender, EventArgs e)
    {
        Button btn = new Button();
        btn.Text = "Test button";
        Panel1.Controls.Add(btn);
        btn.Click += new EventHandler(btn_Click);
    }

    void btn_Click(object sender, EventArgs e)
    {
        Response.Write("<script>alert('test')</script>");
    }
A: 

Make sure you assign an ID to the button, and make sure it's the same everytime you create it.

Create the control in the CreateChildControls overload, adding it once in response to another event isn't going to be enough to keep it on the page.

You're best bet is going to be tracking the whether the button needs to be created or not:

bool CreateButton
{
    get
    {
        if (ViewState["CreateButton"] == null)
            return false;

        return (bool)ViewState["CreateButton"];
    }
    set
    {
        ViewState["CreateButton"] = value;
    }
}

override void public CreateChildControls ()
{
    panel1.Controls.Clear ();

    if (CreateButton)
    {
       Button btn = new Button();
       btn.Text = "Test button";
       btn.ID = "CreatedButton"; // Note the ID here...
       Panel1.Controls.Add(btn);
       btn.Click += new EventHandler(btn_Click);
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    CreateButton = true;
    EnsureChildControls ();
}

void btn_Click(object sender, EventArgs e)
{
    Response.Write("<script>alert('test')</script>");
}

Something like that should work for you...

Kieron
+1  A: 

When you dynamically add controls to your page, you have to re-add them on any subsequent request (postback). The button you added in Button1_OnClick will not automatically be recreated in a subsequent request (e.g. in a postback).

There a lot's of similar questions about this topic, where you can find details. For examples, use the following search:

M4N
what i should do my code behide?
monkey_boys