Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET 4.5
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Amazon Web Services
Analysis Services
Android
Architecture
Arduino
ASP .NET Web API
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
BDD
Big Data
Bing
BizTalk
Book Excerpts
Build and Deploy
Business Intelligence
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE Framework Info - non Technical
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Debugger
Design Patterns
Development Process
Display Technologies
Distributed Computing
Document Database
DotNetNuke
DSL
Dynamic Languages
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
HTML 5
Internet Explorer 8.0
Interviews
IOS
iPhone
Iron Ruby
Java
Java Script
JavaScript
jQuery
JSON
Lightswitch
LINQ
Linux
LUA
Mac OS X
MDX
Messaging
Metro
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
MVVM
MySQL
Network
NHibernate
node.js
NOSQL
Nuget
Object Oriented Development
Objective C
Odata
OLAP
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
PHP
Podcasts
Post Mortem
PowerPoint
Print/Output
Prism
Product News
Product Reviews
Project Management
Prolog
Python
Q&A
Rails
Rake
Razor
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Scheme
Search
Security
Services
SharePoint
SignalR
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server 2012
SQL Server CE/AnyWhere/Mobile/Compact
SSIS
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
TFS
Tips
TypeScript
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 11
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio 2011
Visual Studio 2012
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WebMatrix
WF
Whitepapers
Windows 7
Windows 8
Windows Azure
Windows Live
Windows Phone 7
Windows Phone SDK
Windows Server
Windows Vista
WinForms
WinRT
Workflow
WPF
XAML
Xiine Documentation
XML
XNA
XSLT



LearnNow


XAMALOT
 


Sharepoint TechCon

Reader rating:
Click here to read 11 comments about this article.
Article source: CoDe (2003 - May/June)


Article Pages: < Previous - 1  2 


Dynamically Adding Wired Controls to Web Forms (Cont.)

The Page Event Life Cycle

This is where a thorough understanding of the page event life cycle comes into play. ASP.NET differs from classic ASP in many ways, one of which is the way in which client-side interaction is handled once you submit it back to the server. In classic ASP, the developer handled this process, which meant that the server handled each page in a unique manner. ASP.NET changed this by imposing a structured event life cycle that introduced a uniform series of function members (methods) that are executed consistently each and every time that it renders a Web Form. The function members that handle events are listed and described in Table 1 in the order in which they are processed.

By far, the most commonly used function member listed in Table 1 is the OnLoad() function member. In fact, when you create any type of ASP.NET Web item such as a Web Form or a Web user control, Visual Studio .NET automatically adds this function member to the code behind class for you, whereas you must manually add (override) most of the other function members. In this function member, the current values of the controls on the Web Form are available and code may interact directly with them. Let me state a few very important observations in relation to dynamically created controls.

You can dynamically create controls and wire events into them at any point in the execution process. However, you can only wire events into a control in either the OnInit() function member or in the OnLoad() function member. If the events are encountered at any other point in the cycle of events, it will not cause an exception to be thrown but it will have no affect on the control. The code snippet below shows an example of wiring an event into a control in the OnInit() function.

// Override the OnInit() method.
override protected void OnInit(EventArgs e)
{

  // Dynamically create controls that do not
  // depend upon data on the Web Form.
  Button companyDetailsButton = new Button();
  companyDetailsButton.Click += new EventHandler(this.ShowDetailAccounting);
{

Levels of Events

ASP.NET implements three levels of events: validation, cached, and PostBack

Validation events are handled by validation controls on the client's machine at the page level via snippets of JScript embedded in the page. Validation events will either return a true or false value based upon the success of the validation process. If validation fails, the controls will not allow the page to be posted back to the server.

Depending upon the type of control you use, each ASP.NET Web server control may raise events based upon user interaction. For instance, a DropDownListbox control will raise a SelectedIndexChanged event when the user selects a different option from the DropDownListbox. If the control has its AutoPostBack property set to true, raising certain events will cause the page to be posted back to the server. By default, only the Button, LinkButton, and ImageButton controls automatically cause the page to be posted back to the server. When controls raise events that do not cause the page to be posted back to the server, a note that the event was raised is cached in the ViewState of the page. Cached events are handled in the postback process just after the OnLoad() function member has completed executing.

Click for a larger version of this image.

Figure 3: The CompanyInformation Web Form with dynamically created and wired buttons in the OnLoad() method.

The PostBack event is raised by any control that has its AutoPostBack property set to true. The event raised by the control that caused the postback to occur is handled in the postback process just after the cached events have been processed. The PostBack event is the final event processed in the page event life cycle.

A Limitation to Dynamic Creation

You should know about one important limitation in the sequence that ASP.NET uses to process events that directly impacts my technique for dynamically creating controls. You cannot dynamically create a control and wire an event into it in a cached event or in the PostBack event. ASP.NET processes cached events and the PostBack event after the OnLoad() function member and OnInit() function member have completed processing.

Conclusion

Many complex Web applications require forms to be created and rendered dynamically. The ability to dynamically add controls and content to forms has been an intrinsic feature of both classic ASP and ASP.NET. Microsoft ASP.NET vastly expands the process. Expertise in the dynamic creation process requires a thorough understanding of the ASP.NET page event life cycle.

"
You should not add a control directly to a Web Form because the code generated for the control will be inserted at the end of the HTML stream or just after the </html> closing tag.
"

"
You can only wire events into controls in either the OnInit() function member or the OnLoad() function member; if the control is dependant upon data on the Web Form, then the OnLoad() method is the only option.
"

"
You cannot dynamically create a control and wire an event into it in a cached event or in the PostBack event. Cached events and the PostBack event get processed after the OnLoad() function member and OnInit() function member have completed processing.
"

Shannon A Horn

&


Resources

You'll find additional resources on the Web by searching for the ASP.NET page event life cycle.

Here is an MSDN article that discusses the page event life cycle in detail http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcontrolexecutionlifecycle.asp.

The MSDN Web site lists an article that discusses how to dynamically create Web Form controls: http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q317794. This is the C# version of the code. There is a link at the bottom of the article for the Visual Basic .NET version of the article.



Table 1: The event function members of the page event life cycle in the order that they are processed.
Function MemberDescription
OnInit()Handles the Init event and initializes the Web Form and all of the controls contained on it.
LoadViewState()The ViewState property of all of the server controls are updated to reflect the state of the controls being received from the client. ASP.NET uses the ViewState setting of each control to determine which control values have been modified.
LoadPostData()Process incoming form data.
OnLoad()This is the most commonly used function member in the entire cycle. Controls are created, initialized, and the state is restored.
RaisePostDataChangedEvent()When the state of a control changes, events for each control are fired in response to the data change. These events are fired here.
RaisePostBackEvent()The event that caused the postback is fired.
OnPreRender()This is the last opportunity to interact with controls and form data prior to it being rendered and sent to the client.
SaveViewState()The state of all controls is saved to the encrypted ViewState string that is stored in the hidden control and persisted to the client.
Render()The output of the Web Form is rendered to be sent to the client.
Dispose()Final cleanup opportunity.
OnUnLoad()All server-side references to controls and the page itself are unloaded from memory.


Article Pages: < Previous - 1  2 

Page 1: Intro
Page 2: The Page Event Life Cycle

How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
4.8 out of 5

304 people have rated this article.

Instantly Search Terabytes Of Text
“Lightning Fast”
– Redmond Mag
“Covers all data
sources” – eWeek
25+ fielded & full-text search options
dtSearch’s own document filters highlight hits in popular file types
Web Spider supports static & dynamic data
APIs for .NET, Java, C++, SQL, etc.
Win / Linux (64-bit & 32-bit)
www.dtSearch.com
 

      LearnNow

 

Sharepoint TechCon