Reputation: 115
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);
}
Upvotes: 2
Views: 1348
Reputation: 15893
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.
Upvotes: 1