473,732 Members | 2,207 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Event Handler that creates adds another event handler

I have an ASP.NET page where controls are created dynamically, and I
have an issue where one event handler creates another set of controls,
and then adds event handlers to those controls. The problem comes in
where I need to raise the event in the second control - the event does
not fire. I have distilled the example below down to it simplest:

on Page_Load one button is created, and a Click event hander is added
to the button. When this first button is clicked, it adds another
button and adds another onclick event for this new button.

The first time through, everything works - The first button is
clicked, and then the second button is added with its event handler.
The problem comes on this second postback - the Page_Load event fires,
but not the first button's event - the one the creates the second
button and EventHandler.

How can I get around this? How can I add controls and event handlers
from an event hander? Code is below:

<%@ Page Language="C#" %>

<script runat="server">
protected void Page_Load(objec t sender, EventArgs e)
{
Button button1 = new Button();
button1.ID = "button1";
button1.Text = "Button 1";
button1.Click += new EventHandler(bu tton1_Click);
main.Controls.A dd(button1); // main is the div
}

void button1_Click(o bject sender, EventArgs e)
{
Button button2 = new Button();
button2.ID = "button2";
button2.Text = "Button 2";
button2.Click += new EventHandler(bu tton2_Click);
main.Controls.A dd(button2); // main is the div
}

void button2_Click(o bject sender, EventArgs e)
{
// this event handler is never hit.
}

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>EventHan dler Test</title>
</head>
<body>
<form id="form1" runat="server">
<div id="main" runat="server"> </div>
</form>
</body>
</html>

Feb 22 '07 #1
1 1679
On Feb 22, 2:00 am, kaczm...@gmail. com wrote:
I have an ASP.NET page where controls are created dynamically, and I
have an issue where one event handler creates another set of controls,
and then adds event handlers to those controls. The problem comes in
where I need to raise the event in the second control - the event does
not fire. I have distilled the example below down to it simplest:

on Page_Load one button is created, and a Click event hander is added
to the button. When this first button is clicked, it adds another
button and adds another onclick event for this new button.

The first time through, everything works - The first button is
clicked, and then the second button is added with its event handler.
The problem comes on this second postback - the Page_Load event fires,
but not the first button's event - the one the creates the second
button and EventHandler.

How can I get around this? How can I add controls and event handlers
from an event hander? Code is below:

<%@ Page Language="C#" %>

<script runat="server">
protected void Page_Load(objec t sender, EventArgs e)
{
Button button1 = new Button();
button1.ID = "button1";
button1.Text = "Button 1";
button1.Click += new EventHandler(bu tton1_Click);
main.Controls.A dd(button1); // main is the div
}

void button1_Click(o bject sender, EventArgs e)
{
Button button2 = new Button();
button2.ID = "button2";
button2.Text = "Button 2";
button2.Click += new EventHandler(bu tton2_Click);
main.Controls.A dd(button2); // main is the div
}

void button2_Click(o bject sender, EventArgs e)
{
// this event handler is never hit.
}

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>EventHan dler Test</title>
</head>
<body>
<form id="form1" runat="server">
<div id="main" runat="server"> </div>
</form>
</body>
</html>
Hi,

As you correctly pointed out, the problem is that during the second
postback, the additional button/event handlers are not added to the
page, so no event handlers fire.

If you have a small number of states through which your page can
transition, I'd recommend enumerating those, and tracking which state
your page is in using the viewstate. Then define a routine that
creates appropriate controls based on which state you're in. Then your
button clicks become:

state = newState;
BuildPageContro ls();

and you also call BuildPageContro ls during any postback (so it'll need
to be callable multiple times during a single postback, and not end up
creating duplicate controls)

That's one approach, if you've got a small number of states. If you've
got more complex logic, you may end up having to put more into your
viewstate to allow you to safely reconstruct the page.

Finally, does Button 1 have to add the new Button 2? Could it not just
exist on the page but be disabled?

Damien

Feb 22 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
3601
by: tony kulik | last post by:
This code works fine in ie and opera but not at all in Mozilla. Anybody got a clue as to how to get it right? <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <script language="JavaScript" type="text/javascript"> function show(that) { if (box.style.visibility=='hidden') { that.style.visibility = 'visible'}; }
4
2049
by: Rajiv Das | last post by:
Environment: Visual Studio 2005, Beta 2 ..Net 2.0 Windows XP, SP2 C# Generics ------------------------------- Hi, I have a Windows Form whose contents I would like to dynamically change. I
2
16318
by: JJ | last post by:
Hi All, I need to create a MouseDown event for a picture box . Am I doing the following right? pictureBox.MouseDown += new System.WinForms.MouseEventHandler(pictureBox_MouseDown) Then
6
2877
by: Dan | last post by:
I've created a pocketpc app which has a startup form containing a listview. The form creates an object which in turn creates a System.Threading.Timer. It keeps track of the Timer state using a TimerState object similar to the example in the System.Threading.Timer documentation. The method which handles the timer events, among other things, periodically calls a method in this TimerState object which raises an event to the startup form,...
13
3512
by: Charles Law | last post by:
Mr "yEaH rIgHt" posted the following link about a week ago in answer to my question about removing event handlers. > http://www.vbinfozine.com/t_bindevt.shtml Following on from that post, the following issues still exist. The article shows how to find methods on a receiver that match the pattern OnXXXX given the sender. It loops through the sender events and tries to get methods from the receiver that match the pattern. For each one...
22
16936
by: dvestal | last post by:
Suppose I have this: class C { public delegate void MyEventHandler(); public event MyEventHandler MyEvent; public void foo() { MyEvent(); // NullReferenceException? } }
0
1535
by: arlie_maija | last post by:
Hey - I'm writing a control that contains a DataGrid, and I'm unable to get the update event to fire. When I click the update link, the edit event fires. heres the details... my control overrides CreateChildControls and dynamically creates the DataGrid, creates an EditCommandColumn which it adds to the
1
2239
by: Sin Jeong-hun | last post by:
When you create a new C# project, Visual Studio creates a main form for you. If you double click it, the Visual Studio automatically adds an event handler for the form's Load event. Then you can insert codes into that method. But, you can also override the form's OnLoad method and put that code there, which results in the same result. Since VS.NET does in the first way, it is the recommended way? Is there any performance differences in...
3
2181
by: Tuxedo | last post by:
Is it possible to add a function call to the onUnload event handler from an external js file, or can this only be done via the body tag? In any case, I presume there can only exist one onUnload event handler, which can naturally include any number of function calls. I have instances of html pages, with an existing onUnload event handlers and those without. I'd like to cover both instances, if possible, so that if there is an
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8774
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9447
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9307
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9235
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.