4

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?

3
  • 1
    have you tried to just add the method to the eventlist like: btn.Click += btn_Click;? Commented Aug 20, 2015 at 12:55
  • You have to add your button on every loading of the page, otherwise ASp.NET what's the source of the event that was fired Commented Aug 20, 2015 at 12:56
  • Doesn't work Sebastian, Andrei - I don't want the button there unless another button is clicked, so it's only put in the placeholder on another buttons event click. Commented Aug 20, 2015 at 13:24

1 Answer 1

4

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)
{

}
Sign up to request clarification or add additional context in comments.

9 Comments

I put that in to prevent the post back from firing, removing/changing to true still doesn't fire the event: btn_Click
@thatguy see may edited answer. I am tested this with VS2013.
Thanks, I changed it to load through Page_Load instead of through a another button, and simply set it's visibility property in the button - Accepted.
How to stop the postback?
Thanks for your help, but that just checks if it is a postback - instead of preventing it on the button.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.