Dynamically Adding Controls

Dynamically Adding Controls

‘m a baseball fan. While I’d rather watch a game in person, more often than not, I’m watching it on the television. Something that you may not consciously notice while watching a game on television is the backstop. You see it every time the camera angle from the pitcher’s point of view is displayed. Next time you’re watching a baseball game on television, keep your eye on the advertising billboard on the backstop. You will notice that the advertising changes on a regular basis. Physically at the ballpark there is a blue screen located on the backstop and the advertising is inserted real time during the game for the television viewing audience. The players, coaches, and fans at the ballpark never see the advertising.

You’ve got to admire the marketing genius who came up with this idea. I can imagine someone thinking, “If only there was a way I could sell the same billboard space to more than one advertiser. There’s got to be a way!”

So why am I mentioning this in an article about dynamically adding controls at runtime to an ASP.NET page? Because inserting different advertising messages throughout the game demonstrates exactly the type of thing you can do by adding controls at runtime.

Why Add Controls at Runtime?
This seems like the logical place to start. For anyone who has already found the need to add controls at runtime in a VB, C++, or other Win32 applications, the question may seem fairly fundamental. If you haven’t experienced the need it’s a very valid question. Even experienced developers may not have found the need to add a control at runtime.

Even experienced developers may not have found the need to add a control at runtime.

So, why add controls at runtime? The primary reasons are flexibility and power. Adding controls at runtime provides the flexibility to design user interfaces that can appear and behave differently to different users. Imagine a situation where, depending on the security level of the currently logged on user, certain controls are displayed and others are not. Yes, you could accomplish the same functionality by setting the visible property of the controls but with that solution you’re potentially left with unattractive spaces in the UI where the invisible controls are located. An alternative solution would be to dynamically add the controls at runtime that the user is allowed to work with.

This is just one of a million different scenarios that lend themselves very well to take advantage of the flexibility and power of adding controls are runtime.

Basic ASP.NET Page Architecture
Before you can start adding controls you need to make sure you understand a few architectural issues. ASP.NET pages are built from controls. Everything on the page is a control. Labels, TextBoxes, Command Buttons, DataGrids, static text, and even the HTMLForm are all represented by a control.

The Page.Controls collection contains a reference to every control contained on a page.

   Private Sub cmdSave_Click( _      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles cmdSave.Click         Dim oControl As Control      For Each oControl In Page.Controls         Me.ControlsList(oControl)      Next   End Sub      Private Sub ControlsList(ByVal oPassed As Object)      Dim oControl As Control      Response.Write("Container:"+oPassed.ID+"

") For Each oControl In oPassed.Controls Response.Write(oControl.ID + "

") Next End Sub

The above two procedures contain code that loops through the controls on a form and displays the ID property. The cmdSave_Click loops through the Controls collection on the page and passes each control to the ControlsList procedure, which loops through a container control and lists all the controls.

Adding Controls Programmatically
You add controls to a page (or other container controls as you’ll see shortly) by adding controls to the Controls collection. That seems pretty straightforward to me. You call the Add() method to add a control to the Controls collection. The Add() method causes the control to be appended to the end of the Controls collection. You can add a control to a specific location in the Controls collection by using the AddAt() method.

   Private Sub Page_Load(_      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles MyBase.Load         Dim i As Integer      For i = 1 To 5         Controls.Add(New LiteralControl("Cool
")) Next End Sub

The above code adds five Literal controls that each display the word “Cool” on the page. The resulting Web page appears in Figure 1.

Dynamically Adding User Controls
To start, you’ll create a new Web Form and you’ll add three controls: a descriptive label, a button that will contain the code to add the user control, and a Placeholder control (see Figure 2).

Next, you’ll create a user control named PlaceHolderDemoUserControl that you’ll dynamically add to the page you just created. The user control consists of an HTML table and Web controls to create a typical data entry form (see Figure 3).


Figure 2. The PlaceholderDemo Page: This page contains the phDemo Placeholder control and a button that, when clicked, adds a user control to phDemo.
?
Figure 3. The PlaceholderDemoUserControl: This user control will be loaded into the phDemo placeholder control at runtime.

With your user control created it’s time to write the code that will add it to your form at runtime (see Listing 1).

There are three key lines in Listing 1. The first creates the oCtrlDemo variable.

   Public oCtrlDemo As Control

The oCtrlDemo variable is the control that is added to the Placeholder control. The second line loads the user control into the oCtrlDemo variable.

   Me.oCtrlDemo = _      LoadControl("PlaceholderDemoUserControl.ascx")

And the third key line adds the oCtrlDemo control into the phDemo placeholder.

   Me.phDemo.Controls.Add(Me.oCtrlDemo)

That’s it. When the user clicks on the button the PlaceholderDemoUserControl is loaded into the oCtrlDemo control and then it is added to the phDemo placeholder by calling the Add method on the phDemo Controls collection.

While the Add method is great for adding a control at runtime, it doesn’t offer you a lot of help in designating where the control will appear on the page.

Sooner or later you are going to want to reference properties on the user control. Working with properties native to the Control class that the oCrtlDemo control is based on is very straightforward. You just assign or retrieve the property value like you would with any other object.

   Private Sub Button1_Click(_      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles Button1.Click         Me.oCtrlDemo = _         LoadControl("PlaceholderDemoUserControl.ascx")      Me.oCtrlDemo.Visible = False      Me.phDemo.Controls.Add(Me.oCtrlDemo)   End Sub

You can see in the code above that the Visible property of the oCtrlDemo object has been set to False. Since Visible is a native property of the Control class this will work fine. The end result of this code is that the oCtrlDemo control will be added to the placeholder but it will not be visible.

Working with the properties native to the Control class is all well and good, but let’s add a custom property named DemoProp to the PlaceholderDemoUserControl (see Listing 2). It just takes a simple step in order to access the DemoProp property. You’ll covert the oCtrlDemo class to the type of class you added to it, namely the PlaceholderDemoUserControl. The following code demonstrates how to do this.

   Private Sub Button1_Click(_      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles Button1.Click         Me.oCtrlDemo = _         LoadControl("PlaceholderDemoUserControl.ascx")      CType(Me.oCtrlDemo, _         PlaceholderDemoUserControl).DemoProp = 10      Me.phDemo.Controls.Add(Me.oCtrlDemo)   End Sub

In this code, the key is to make sure that you convert the oCtrlDemo object from a plain Control object into an object of type PlaceholderDemoUserControl, so you’ll use the CType() function. Once you’re done you can access the custom property, DemoProp.

I’ll suggest one more change here just to drive home the point of working with properties on user controls. In this next code snippet, I’ll add a line to the Page_Load method of the PlaceholderDemoControl user control that will set the Age textbox to the value in the DemoProp property.

   Private Sub Page_Load(_      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles MyBase.Load         Me.txtAge.Text = Me.DemoProp   End Sub

As you’ve seen so far, working with the Placeholder control and dynamically adding controls at runtime is not that difficult. Next, you can take what you’ve learned and extend it into a page template.

Adding Body User Controls
When the page loads for the first time, the Body query string variable will be blank and will result in neither of the body user controls being added (see Figure 11). In this situation you could load a “home” user control to display the initial content. I’ll leave that as an exercise for you.

So, how does the Body query string variable get set? The links in the Navigation user control hold the answer to this question.

   Body #1   Body #2   Body #2

Setting the CommandArgument for each LinkButton to 1, 2, or 3 determines which Body user control to display. In addition, each LinkButton has its Click event handled by the FilterLetter_Click method.

   Private Sub FilterLetter_Click(_      ByVal sender As System.Object, _      ByVal e As System.EventArgs) _      Handles LinkButton1.Click, _      Linkbutton2.Click, _      Linkbutton3.Click         If sender.CommandArgument = 1 Then         Response.Redirect("Formtemplate.aspx?Body=1")      ElseIf sender.CommandArgument = 2 Then         Response.Redirect("Formtemplate.aspx?Body=2")      ElseIf sender.CommandArgument = 3 Then         Response.Redirect("Formtemplate.aspx?Body=3")      End If   End Sub

In this code the FormTemplate page is posted to and the Body query string gets passed into it.

Contained in the Page_Load is where the Body query string is captured and subsequently passed into the BodySetup method.

   Dim strBodyCode As String = _      Request.QueryString("Body")   Me.HeaderSetup()   Me.FooterSetup()   Me.NavigationSetup()   Me.BodySetup(strBodyCode)

Let’s walk through a typical user action. Clicking on the Body #3 LinkButton on the Navigation bar causes a “3” to be posted back to the FormTemplate page. This in turn causes a “3” to be passed into the BodySetup method causing the Body3.ascx user control to be loaded into the plhBody placeholder. The resulting page is in Figure 12.


Figure 11: The FormTemplate Page. This page displays when a Body query string variable is not passed in.
?
Figure 12: The FormTemplate Page. This page displays when the Body query string variable is set to 3.

Obviously the template you created here is just one of an infinite number of templates you can design and build yourself for your ASP.NET Web sites.

Well that wraps up this article. I’m always interested to hear your feedback about the material covered here. As you can see, working with the Placeholder control and adding controls at runtime provides you with the flexibility to design generic templates and the power to leverage them over and over again.

devx-admin

devx-admin

Share the Post:
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

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

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,

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

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

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

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

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

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

Sitemap