0

I created a button from code behind:

Panel dynamicPanel = new Panel();
Button dynamicButton = new Button();
dynamicButton.Text = "View";            
dynamicButton.Click += new EventHandler(dynamicButton_Click);
dynamicPanel.Controls.Add(dynamicButton);
dynamicDiv.Controls.Add(dynamicPanel);

and the OnClick method:

protected void dynamicButton_Click(object sender, EventArgs e)
{
    Response.Write("view button response");
    string script = "alert(\"view clicked.\");";
    ScriptManager.RegisterStartupScript(this, GetType(), 
        "ServerControlScript", script, true);
}  

When I click the button, there is postback (IsPostback with Javascript alert) but the EventHandler is not fired. I can say that content that was visible on the page disappears if that is a clue.

I need to create this in a custom protected void method.

8
  • 2
    maybe you should use JavaScript instead of C# for such dynamic. And if you use MVC, implementing dynamic is also easier. Commented Feb 10, 2017 at 0:48
  • @LeiYang Don't know MVC. Can you give Javascript example? The problem is that dynamicPanel is created for each item in a list. So there are several of these on the page. Commented Feb 10, 2017 at 1:34
  • Webforms is out of date, it is not Winform so better start with MVC now. Commented Feb 10, 2017 at 1:36
  • @LeiYang Sorry, cannot do. The website is already running. This work here is just adding custom features. Commented Feb 10, 2017 at 1:38
  • @matt2605: What is the reason that you use code behind instead of writing your event handler on the client side? Commented Feb 10, 2017 at 2:43

1 Answer 1

1

Your code looks a bit weird to me, but as for the problem "When I click the button, the method is not fired": Try renaming the method dynamicREGButton_Click() to dynamicButton_Click().

I assume you have a method dynamicButton_Click() in your code already; otherwise, you could not compile. However, the method you register via dynamicButton.Click += new EventHandler(...); is the method you call. The code you showed us doesn't match in that regard.

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

2 Comments

I've made the edit dynamicREGButton_Click() should have been dynamicButton_Click(). And you're right that it would not compile otherwise. I just want the button to work first before I set the code properly.
I've edited it again to clarify the "fired" meaning.

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.