2

I am trying to call dynamically created button click event. I this event I want to show one message on clicking dynamically created button.

my Code

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnMain_Click(object sender, EventArgs e)
    {

        Button btnNew = new Button();
        btnNew.ID = "btnClick";
        btnNew.Text = "Click";

        btnNew.Click += new System.EventHandler(btnNew_Click);
        this.form1.Controls.Add(btnNew);

    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        Label lblMeaaseg = new Label();
        lblMeaaseg.ID = "txtMessage";
        lblMeaaseg.Text = "Hello Shree";
        this.form1.Controls.Add(lblMeaaseg);
    }
10
  • 3
    Welcome to StackOverflow! As you will quickly learn, "doesn't work" is not a valid description of what is wrong with your code. Please provide the exact text of the error you are receiving and the line where it is occurring, as applicable Commented Mar 20, 2015 at 13:16
  • I want to show this lblMessage on btnNew_Click(object sender, EventArgs e) event but it is not working Commented Mar 20, 2015 at 13:25
  • You may have to add location of the label. Commented Mar 20, 2015 at 13:34
  • this.form1.Controls.Add(lblMeaaseg); this is location that I want to display the label Commented Mar 20, 2015 at 13:51
  • @RyanDansie - what does it have to do with ViewState? Commented Mar 20, 2015 at 16:44

1 Answer 1

1

You create the dynamic button in the click event handler of btnMain during the postback caused by btnMain click. After that you see the new button in the browser page, click it and expect its click event handler (btnNew_Click) to fire. Pressing the new dynamic button causes a new postback that is processed by a new instance of the page created on the server by ASP.NET. This new page does not have the dynamic button - there is nothing there connected to btnNew_Click. You have to write code that persists the fact that the dynamic button has been created and recreates this button every time the page is instantiated. So that this button has a chance to feel and respond to its client-side click.

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

Comments

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.