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.

See also  Comparing different methods of testing your Infrastructure-as-Code

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



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


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.


Process incoming form data.


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


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


The event that caused the postback is fired.


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


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


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


Final cleanup opportunity.


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.

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

The MSDN Web site lists an article that discusses how to dynamically create Web Form controls:;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.

See also  Comparing different methods of testing your Infrastructure-as-Code

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist

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