Dynamic Event not firing on button click.

I have a problem in calling a dynamically contructed event on a button click(which is also dynamic).

I have an server side ASP.NET button when clicked generates two dynamic buttons, 'Yes' and 'No'. When clicked on one of these two buttons i need to call an dynamically contructed event which i am unable to call. Not sure what the problem is. Clicking on Yes must display 'Hello' and click on No must display 'Hi'. I have to call that event.

Below is the code i have written.

C# code:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

 

}

protected void btnNextYes_Click(object sender, EventArgs e)

{

Response.Write(
"Hello");

}

protected void btnNextNo_Click(object sender, EventArgs e)

{

Response.Write(
"Hi");

}

protected void Button1_Click(object sender, EventArgs e)

{

CreateControls();

}

private void CreateControls()

{

Label lblNextQuestion = new Label();

//lblNextQuestion.ID = "lblNextQuestion";// +next;

//lblNextQuestion.Text = question;

Button btnNextYes = new Button();

btnNextYes.ID = "btnNextYes123";// +next;

btnNextYes.Text = "Yes";

btnNextYes.Click += new EventHandler(btnNextYes_Click);

btnNextYes.CommandArgument = "btnNextYesArg";

btnNextYes.CommandName = "btnNextYesCmdName";

Button btnNextNo = new Button();

btnNextNo.ID = "btnNextNo123";// +next;

btnNextNo.Text = "No";

btnNextNo.Click += new EventHandler(btnNextNo_Click);

btnNextNo.CommandArgument = "btnNextNoArg";

btnNextNo.CommandName = "btnNextNoCmdName";

Label lblNextQuestionSolution = new Label();

lblNextQuestionSolution.ID = "lblNextQuestionSolution";// +next;

//lblNextQuestionSolution.Visible = false;

//lblNextQuestionSolution.Text = solution;

pnlNextQuestionPanel.Controls.Add(lblNextQuestion);

pnlNextQuestionPanel.Controls.Add(btnNextYes);

pnlNextQuestionPanel.Controls.Add(btnNextNo);

pnlNextQuestionPanel.Controls.Add(lblNextQuestionSolution);

this.form1.Controls.Add(pnlNextQuestionPanel);

}

}

ASPX Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

<asp:Panel ID="pnlNextQuestionPanel" runat="server" Height="50px" Width="125px">

</asp:Panel>

</div>

</form>

</body>

</html>

 

Please help me in this regard.

Many thanks in advance.

0
sateesh_seelam
12/5/2008 5:32:16 AM
asp.net.web-forms 93655 articles. 6 followers. Follow

3 Replies
2476 Views

Similar Articles

[PageSpeed] 10
Get it on Google Play
Get it on Apple App Store

You must recreate dynamically created control on every post back. So, add this in Page_Load event:

        if (ViewState["AddControls"] != null)
        {
            CreateControls();
        }
and add this at the end of CreateControls() function:
ViewState["AddControls"] = true;

0
kipo
12/5/2008 9:03:45 AM

 It is Correct but there is a minor Problem

When  you check viewstate and call function it render yes and no buttons when button click event call it render again

then multiple yes and no buttons shows 

so use this on page load

make viewstate null on page load

if (ViewState["AddControls"] != null)
{
            CreateControls();
            ViewState["AddControls"] = null;

}


Please Don't forget to click "Mark as Answer" on the post that helped you and Find the correct Answers to Others Easily.

Thanks,
Muhammad Owais Nadiadwala
Software Engineer
Salsoft Technologies
Cell: +923332366692
Email: mohammadowais@msn.com
0
os123
12/5/2008 9:49:10 AM

os123:

 It is Correct but there is a minor Problem

When  you check viewstate and call function it render yes and no buttons when button click event call it render again

then multiple yes and no buttons shows 

so use this on page load

make viewstate null on page load

if (ViewState["AddControls"] != null)
{
            CreateControls();
            ViewState["AddControls"] = null;

}

Good point, but wrong code. If he would use that code, he wouldn't achieve his first goal. So, right thing to do would be to modify Button1_Click event like this:
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (ViewState["AddControls"] == null)
        {
            CreateControls();
        }
    }

0
kipo
12/5/2008 10:16:50 AM
Reply:

Similar Artilces:

An OnClick event doesn't fire up when a button is clicked in a Tab Panel in a Tab Container in an AJAX Web Form
Hello Post: I would like to enclose the following code so you can analize what is going on: "> " style="vertical-align:top;"> "> "> ...

How to fire events in other web form from other web form ?
Suppose that I have A and B web form. I want to trigger B web form's Page_Load event from A web form. How can I do that ? Thanks in advanced WilbertWilbert Bujn Create a public method in B that call the load method : public void Load(object sender, System.EventArgs e) { Page_Load(sender, e) ; } In the page_load of A, instanciate a B object and then call the function B myB = new B() ; myB.Load() ; Quicky Thank you quicky, it works fine. WilbertWilbert Bujn...

button click event not firing for dynamic buttons added on PreRender of the updatepanel
Hi,i have a webpage with an updatepanel updatepanel1.i am adding controls dynamically to the updatepanel on the prerender event.i am using the prerender event as i want to get the latest bata from thedatabase which include the data i have inserted on my last button click.But the button click event is not getting trigged on clicking the button.Here is the sample code in PreRenderSqlCommand cmd = new SqlCommand("SELECT Heading, ID FROM tblNews ORDER BY ID;", conn);conn.Open();SqlDataReader sqlData =cmd.ExecuteReader(CommandBehavior.CloseConnection);while (sqlData.Read()){lblHeading =...

button click event from another button click not firing
 Hi,  I want to trigger a button click event from another button click .It is not firing.  Please help.  protected void btnReview_Click(object sender, EventArgs e) {       if (MandatoryValidation())        {         this.Button1.Click += new System.EventHandler(this.Button1_Click);       } }protected void Button1_Click(object sender, EventArgs e) { } protected void btnReview_Click(object sender, EventArgs e){   &...

Dynamically loaded user control with a button doesn't fire its button click event?
I have a datagrid, in which one of the columns is 'button' column called 'Send Email'. When I click on this button, then an email user control is dynamically loaded into a placeholder above the datagrid header area. The email control renders correctly, but when I click on 'Send' button in this user control, then the click event of this 'Send' button doesn't fire. This is even though the 'Handles.btnSend.Click' is there for the click method of the 'Send' button. Can someone please tell me why the event is not firing and what do I need to do to make it fire?    sun21170 you have...

Dynamically loaded Web User Control .ascx button click event handler not called on second time click
I have an ascx control (that performs actions for an entity) being added dynamically to accordion panes, and then the panes are added to an ajax accordion control, so that the accordion can contain multiple panes with each pane containing one ascx control. The ascx control contains a delete button which removes the entity from the database. Once the entity is removed, I need to reflect this deletion in the parent page by removing the accordion pane from the accordion. To do this I created a delegate function and which is called from the parent page to rebind the accordion and hence not d...

button click event not firing on dynamic usercontrol
Hi, I have a page that adds a user control dynamically (in the code behind).This usercontrol contains a small form and two buttons: save and cancel When opening the aspx page the usercontrol displays perfect, but when I click the save (or cancel) button nothing happens. It does a postback but it doesn't fire the onclick handler of the button clicked.When I set debug points in the onload and onclick handlers, only the onload event is hit when dynamically loading the usercontrol in the page.When clicking the save or cancel button no debug points are hit.When I create a test page and add ...

Click event not fired for dynamic image button
 Hi...   I have created one website with master and content pages ...On Master page I have created some dynamic image button controls on load event i have created array of image buttons and taken one placeholder on web page then i have added image buttons on placeholder with while loop and added placeholder on web page .    but my problem is that the click event for dynamic generated image button is not fired , it is like Unreachable code.my code on master page isprotected void Page_Load(object sender, EventArgs e)  {         ...some da...

Cannot get a click event fired for a dynamic button...
Hello all, I am pulling my hair out trying all sorts of different ways to do what seems so simple.I have been searching numerous forums seeking the answer but none have worked. I am not completely new to programming but relatively new to .Net.I have created a user control that generates a file upload panel in code. It is a panel that dynamically creates its controls at run-time. The reason I generate controls in code is that i need to change the file-upload display depending upon which page calls it.Here is the entrie code for analysis: Partial Class fileLoader    Inherit...

How to fire the button click event in web part?
If I created a button control programmatically in a web form, I would use   public Button btnSearch = new Button();protected override void CreateChildControls(){ Button1.Click += new System.EventHandler(this.Button1_Click); this.Controls.Add(Button1); } protected void Button1_Click(object sender, EventArgs e) { //code here. }It doesn't work in a web part. It bombed at this.Controls.Add(Button1); after I clicked the button. How does the button click event get fire in web part? Thanks.DY  Im a bit confused here.. can you elaborate more? What really is your re...

Multiple Button controls on form not firing Click event
There is probably a better way to do this, but here is what is going on. Imagine two "div" sections that contain images that have been tiled. One div contains all of the images that belong to a product, the other div contains the library of images you may want to assign to the product. Under each image in the library section is a Button control "Add". Under each image in the "Assigned to product" div there is a "Remove" Button control to remove it from the product. I'm trying to provide functionality where the user can simply click "Add&q...

Dynamically adding buttons to web form and wiring up the onclick event.
I have a web form that is generated at runtime with a number of dynamically created buttons. Creating the buttons is easy, but wiring them up is not. I would love to use the cold behind and a single onclick event. Then based on the id, I can call a single method that does an operation. Each button will perform the same tasks. The user can chose one of three tasks. I though I would either have a dropdown or three radio buttons for this. Alternatively, I could have some javascript, but I am not quiet sure how to post back with javascript and if all the buttons will make it more difficult. Does...

Button click event not fired for a custom webpart where controls are added dynamically.
We are migrating a Sharepoint 2003 site to MOSS 2007 and ASP.NET 2.0. We have also migrated the webparts but they are still inheriting from Sharepoint.WebPart. We have a webpart where controls are added dynamically at runtime. On this webpart a button is added dynamically and a click event handler is also attached. The button on the webpart is displayed only when there is some data. The button deletes the selected row of data when clicked. But when we click on the button, the page gets posted but the event handler is not called. We analysed and found that the code where we add the button to ...

create Link buttons Dynamically inside the Calendar and Fire Click Event
Hi ,      In my application i need to develop calendar control containing link buttons clicking on the link it should redirect to other page. please see the below code dateDisplayed method is calling  from OnDayRender Method protected void DateDisplayed(object source , DayRenderEventArgs e) { ...................... foreach (DataRow dRow in ds.Tables["WorkGroup"].Rows) { DateTime compareDate = Convert.ToDateTime(dRow["Act_StarDateTime"]); compareDate = Convert.ToDateTime(compareDate.ToShortDateString()); if (DateTime.Compare(compareDate, Convert.ToDateTime(...

Web resources about - Dynamic Event not firing on button click. - asp.net.web-forms

Dynamics - Wikipedia, the free encyclopedia
Brownian dynamics , the occurrence of Langevin dynamics in the motion of particles in solution (e.g. a grain in water, as was first seen by Brown); ...

Datacenter Dynamics
Datacenterdynamics for data center information, conferences, news, videos, whitepapers and reports globally

Dynamic Chiropractic - chiropractic, news, articles, research & information for chiropractors - Find ...
Dynamic Chiropractic - chiropractic, news, articles, research & information for chiropractors - Find a Chiropractor

Playing ‘GTA V’ in a Force Dynamics motion simulator looks like a ton of fun
It's been a few weeks since I last sat down and played Grand Theft Auto V . Although it's still one of my favorite games of both this generation ...

Microsoft Dynamics CRM chief steps down
... with heavyweight Salesforce, SAP and Oracle, the head of the company's CRM division this week announced plans to step down. Microsoft Dynamics ...

Dynamic duo: Can Paul Ryan and Barack Obama work together?
Christian Science Monitor Dynamic duo: Can Paul Ryan and Barack Obama work together? Christian Science Monitor As newly elected Speaker of ...

Considering Group Dynamics in Agile Adoption
... and nations have personality traits based on their life positions . Berne further expanded his concepts in his book Structure and Dynamics of ...

The Republicans’ dynamic deception for 2016
... the media: Well, the numbers the Tax Foundation had put out is that the static cost of the plan is $3.6 trillion over 10 years, but the dynamic ...

Microsoft Dynamics AX delivers the power of the cloud to businesses
Microsoft has announced that the next release of its flagship ERP solution, Microsoft Dynamics AX, will be generally available in the first quarter ...

Master and Dynamic's MW60s are a stellar mix of style and sound
My first experience with Master &amp; Dynamic's audio gear was the time I spent with the MH40 wired headphones this summer. I noticed the company's ...

Resources last updated: 11/21/2015 3:45:31 PM