thatguy
thatguy

Reputation: 99

Dynamically created Button not calling event c#

Button won't call it's event.

called in another button:

placeHolder.Controls.Add(CreateButton());

create button:

public Button CreateButton()
{
    Button btn = new Button();
    btn.ID = "id";
    btn.Text = "some text";
    btn.Attributes.Add("onclick", "return false;");
    btn.Click += new EventHandler(btn_Click);
    return btn;
}

Functionality:

private void btn_Click(object sender, EventArgs e)
{
     // do something.
}

places debug lines to find the source, it's simply not calling btn_Click() when clicked. What's missing?

Upvotes: 4

Views: 747

Answers (1)

Mitat Koyuncu
Mitat Koyuncu

Reputation: 928

This code prevents the click event from firing:

btn.Attributes.Add("onclick", "return false;");

Remove this code, or change it to:

btn.Attributes.Add("onclick", "return true;");

EDIT

I am tried this code and it worked correctly. PlaceHolder is in form tag and runat attribute is server:

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
        placeHolder.Controls.Add(CreateButton());
}

public Button CreateButton()
{
    Button btn = new Button();
    btn.ID = "id";
    btn.Text = "some text";
    btn.Click += btn_Click;
    return btn;
}

private void btn_Click(object sender, EventArgs e)
{

}

Upvotes: 4

Related Questions