Dynamically Adding Wired Controls to Web Forms

Dynamically Adding Wired Controls to Web Forms

eb Forms that require only controls and functionality provided by the built-in ASP.NET Web server controls are easy to create. But creating Web Forms that require or are designed with extended controls and functionality can be a challenge.

In 2000, I worked on a client database in SQL Server that included 134 tables. I designed the application so that the client could use stored procedures to access all data. In my design, each table had a minimum of four stored procedures for working with its data. Such stored procedures common to each table are referred to as either the NURD (New, Update, Read, Delete) stored procedures for the table or the CRUD (Create, Read, Update, Delete) stored procedures for the table depending on who you ask.

Many times the code contained in these stored procedures would be extremely repetitious with the only difference between the New/Create stored procedures for each table being table and column names while the rest of the code remained the same. This also applies to the other types of stored procedures for each table. Each table could then have additional stored procedures beyond the NURD stored procedures. Since there is so much repetition between the types of stored procedures from table to table, the task of creating these stored procedures turns into a lengthy period of copying, pasting, modifying, and saving code several hundred times.

The development team I worked with estimated that we would spend approximately 90 hours to create the NURD stored procedures. We dreaded this mundane task. As a solution, my team created an automated stored procedure builder using classic ASP and SQL Distributed Management Objects (SQL-DMO). I’ll outline how this tool was created in a future article.

In 2001 (.NET beta 2), I migrated this automated stored procedure builder from classic ASP to ASP.NET and consolidated it from a series of classic ASP Web pages to a single ASP.NET Web Form. Although I was working on other ASP.NET projects as well, through this migration I learned some important things about ASP.NET. The most significant thing I learned related to the event life cycle of ASP.NET Web Forms.

An Example Scenario
The migration project mentioned above requires too much explanation and would take this article down a different road than intended, so I’ll use a sample Web Form to illustrate the principles that I will teach you.

My sample Web Form simply lists some company types in a drop down list box. Once you select a type of company, the form lists all of the companies for the selected type. Although the migration project above employed custom button type controls, this sample application uses built-in Web server buttons that you can click to display details for a company from those listed, as shown in Figure 1.

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.

Function Member

Description

OnInit()

Handles the Init event and initializes the WebForm and all of the controls contained on it.

LoadViewState()

The ViewState property of all of the servercontrols are updated to reflect the state of thecontrols being received from the client. ASP.NETuses the ViewState setting of each control todetermine which control values have been modified.

LoadPostData()

Process incoming form data.

OnLoad()

This is the most commonly used function member inthe entire cycle. Controls are created,initialized, and the state is restored.

RaisePostDataChangedEvent()

When the state of a control changes, events foreach control are fired in response to the datachange. These events are fired here.

RaisePostBackEvent()

The event that caused the postback is fired.

OnPreRender()

This is the last opportunity to interact withcontrols and form data prior to it being renderedand sent to the client.

SaveViewState()

The state of all controls is saved to theencrypted ViewState string that is stored in thehidden control and persisted to the client.

Render()

The output of the Web Form is rendered to be sentto the client.

Dispose()

Final cleanup opportunity.

OnUnLoad()

All server-side references to controls and thepage itself are unloaded from memory.

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 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 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.

Dynamic Control Creation Limits

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.

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.

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.

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 detailhttp://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.

devx-admin

devx-admin

Share the Post:
Apple Tech

Apple’s Search Engine Disruptor Brewing?

As the fourth quarter of 2023 kicks off, the technology sphere is abuzz with assorted news and advancements. Global stocks exhibit mixed results, whereas cryptocurrency

Revolutionary Job Market

AI is Reshaping the Tech Job Market

The tech industry is facing significant layoffs in 2023, with over 224,503 workers in the U.S losing their jobs. However, experts maintain that job security

Foreign Relations

US-China Trade War: Who’s Winning?

The August 2023 visit of Gina Raimondo, the U.S. Secretary of Commerce, to China demonstrated the progress being made in dialogue between the two nations.

Pandemic Recovery

Conquering Pandemic Supply Chain Struggles

The worldwide coronavirus pandemic has underscored supply chain challenges that resulted in billions of dollars in losses for automakers in 2021. Consequently, several firms are

Game Changer

How ChatGPT is Changing the Game

The AI-powered tool ChatGPT has taken the computing world by storm, receiving high praise from experts like Brex design lead, Pietro Schirano. Developed by OpenAI,

Apple Tech

Apple’s Search Engine Disruptor Brewing?

As the fourth quarter of 2023 kicks off, the technology sphere is abuzz with assorted news and advancements. Global stocks exhibit mixed results, whereas cryptocurrency tokens have seen a substantial

GlobalFoundries Titan

GlobalFoundries: Semiconductor Industry Titan

GlobalFoundries, a company that might not be a household name but has managed to make enormous strides in its relatively short 14-year history. As the third-largest semiconductor foundry in the

Revolutionary Job Market

AI is Reshaping the Tech Job Market

The tech industry is facing significant layoffs in 2023, with over 224,503 workers in the U.S losing their jobs. However, experts maintain that job security in the sector remains strong.

Foreign Relations

US-China Trade War: Who’s Winning?

The August 2023 visit of Gina Raimondo, the U.S. Secretary of Commerce, to China demonstrated the progress being made in dialogue between the two nations. However, the United States’ stance

Pandemic Recovery

Conquering Pandemic Supply Chain Struggles

The worldwide coronavirus pandemic has underscored supply chain challenges that resulted in billions of dollars in losses for automakers in 2021. Consequently, several firms are now contemplating constructing domestic manufacturing

Game Changer

How ChatGPT is Changing the Game

The AI-powered tool ChatGPT has taken the computing world by storm, receiving high praise from experts like Brex design lead, Pietro Schirano. Developed by OpenAI, ChatGPT is known for its

Future of Cybersecurity

Cybersecurity Battles: Lapsus$ Era Unfolds

In 2023, the cybersecurity field faces significant challenges due to the continuous transformation of threats and the increasing abilities of hackers. A prime example of this is the group of

Apple's AI Future

Inside Apple’s AI Expansion Plans

Rather than following the widespread pattern of job cuts in the tech sector, Apple’s CEO Tim Cook disclosed plans to increase the company’s UK workforce. The main area of focus

AI Finance

AI Stocks to Watch

As investor interest in artificial intelligence (AI) grows, many companies are highlighting their AI product plans. However, discovering AI stocks that already generate revenue from generative AI, such as OpenAI,

Web App Security

Web Application Supply Chain Security

Today’s web applications depend on a wide array of third-party components and open-source tools to function effectively. This reliance on external resources poses significant security risks, as malicious actors can

Thrilling Battle

Thrilling Battle: Germany Versus Huawei

The German interior ministry has put forward suggestions that would oblige telecommunications operators to decrease their reliance on equipment manufactured by Chinese firms Huawei and ZTE. This development comes after

iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and design compared to its predecessors.

Chip Overcoming

iPhone 15 Pro Max: Overcoming Chip Setbacks

Apple recently faced a significant challenge in the development of a key component for its latest iPhone series, the iPhone 15 Pro Max, which was unveiled just a week ago.

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new model, three essential features come

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years, as reported by energy analytics

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW) of wind, solar, and energy

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and wind sources. This funding will

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.

Sitemap