ASPNET Web Forms User Controls

ASP.NET Web Forms: User Controls

Table of Contents

Web Forms are web pages that execute on the server and generates output to the browser. It is flexible and allows creating and adding custom controls.

Web Forms are made up of two components: the visual portion (the ASPX file), and the code behind the form resides in a separate class file.

A User Control is a reusable page/control with an extension of .ascx and created similar to a .aspx page, but the difference is that a User Control does not render on its own; it requires a .aspx page to be generated.

Create User Control in ASP.NET:

Step 1: Right-click on the Solution Explorer project then select Add New Item > Web User Control template.

C:\Users\om\AppData\Local\Microsoft\Windows\INetCache\Content.MSO\A9D35F7.tmp

Click on Add button. After this User Control will be added into the solution of the application. Open the design mode and add components like two textboxes, one label, and one button and after adding the studentcontrol.ascx the source code will be:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="StudentUserControl.ascx.cs" Inherits="StudentUserControl" %>  
<h3>This is User Contro1   </h3>   
<table>    
<tr>  
<td>Name</td>  
<td>    
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>  
</td>  
</tr>  
<tr>  
<td>City</td>  
<td><asp:TextBox ID="txtcity" runat="server"></asp:TextBox></td>  
</tr>  
<tr>  
<td></td>  
<td>  
     </td>  
</tr>  
<tr>  
<td></td>    
<td>   
    <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnClick" />  </td>  
</tr>  
</table><br />  
 <asp:Label ID="lblServer" runat="server" ForeColor="White" Text=" "></asp:Label> 

In the above, there is no HTML code such as head, body and form in User Control then it will create the server control. Switching to design mode the control will be:

C:\Users\om\AppData\Local\Microsoft\Windows\INetCache\Content.MSO\804ECA1D.tmp

Now click on the save button and write the below code in the studentusercontrol.ascx.cs file:

protected void btnClick(object sender, EventArgs e)  
{  
    lblServer.Text="Your Name is "+txtName.Text+" and you are from  "+txtcity.Text;  
}

In the above code, whenever the user enters text into the preceding text boxes, it is displayed on the label after clicking on the save button. Now you are ready with the User Control when you try to run it in a browser, as shown in the following error:

C:\Users\om\AppData\Local\Microsoft\Windows\INetCache\Content.MSO\D6173F33.tmp

As a User Control does not run directly on its own. For rendering a User Control, you must use it in a .aspx page, now add the User Control in the .aspx page. 

Step 3: Add User Control into .aspx page 

We will add the User Control into a .aspx page to use it, so right-click on the Solution Explorer project and add the Default.aspx page. After the addition of the .aspx page then the Solution Explorer will be:

C:\Users\om\AppData\Local\Microsoft\Windows\INetCache\Content.MSO\185072B9.tmp

Registering User Controls on an ASP.NET web form:

To use a User Control in a .aspx, we need to register it using the Register page directive. The register page directive contains the following properties:

C:\Users\om\AppData\Local\Microsoft\Windows\INetCache\Content.MSO\ADE79E2F.tmp
  • Assembly: It is an optional property used to register the assembly; for example, the Ajax control toolkit.
  • Namespace: It is used to specify the namespace.
  • Src: It is used to set the source of User Control.
  • TagName: It is used to provide the name for the User Control used on a page.
  • TagPrefix: It is used to specify the prefix name of User Control that is similar to ASP. You can define any prefix name.

Now let us register the User Control in an .aspx page. Go to the default.aspx source code and then to the top of the source code and the Register property and select it. If the User Control is not shown click on or pick the URL as:

C:\Users\om\AppData\Local\Microsoft\Windows\INetCache\Content.MSO\DE21B715.tmp

After clicking on the Pick URL, the following window is shown, browse to the User Control’s file location, select it and click on the OK button:

C:\Users\om\AppData\Local\Microsoft\Windows\INetCache\Content.MSO\B1BECEEB.tmp

After clicking on the OK button, the User Control file path will be added to the register directive. After we define the tagname and tagprefix, the Register directive will be:

C:\Users\om\AppData\Local\Microsoft\Windows\INetCache\Content.MSO\49D47331.tmp

Now enter the TagPrefix into the form section then the control will be shown as:

C:\Users\om\AppData\Local\Microsoft\Windows\INetCache\Content.MSO\B0770D67.tmp

Select the control and define the properties like runat and Id. After defining it, the User Control will be:

<uc:Student ID="studentcontrol" runat="server" />
The code of the default .aspx code is given below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">    
<%@ Register Src="~/StudentUserControl.ascx" TagPrefix="uc" TagName="Student"%>     
<html xmlns="https://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">    
    <title>Article </title>    
</head>    
<body bgcolor="blue">    
    <form id="formSubmit" runat="server">    
    <div style="color: White;">    
        <h4>    
            Article for ASP.NET 
 </h4>     
      <uc:Student ID="studentcontrol" runat="server" />    
    </div>  
    </form>  
      </body>  
</html>

Registering User Controls at the web.config file:

Sometimes you might want to use user controls in multiple pages in a .Net application. At this point, you do not want to keep on registering user controls on every ASP.Net page. You can create the registration in the web.config file.

The web.config file is a standard configuration file used by all web pages. It contains necessary configuration details. For example, one standard configuration in the web.config file is the target framework parameter, and this parameter is used to identify the version of the .Net framework used by the application.

Step 1: Open the web.config file.

Creating Asp.net Controls, Webforms and Web config file

Step 2: Now register the components in the web.config file by using the below code:

<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<pages>
<controls>
<add tagPrefix="TWebControl" src ="~/ExampleControl.ascx" tagName="WebControl"/>
</controls>
</pages>
</system.web>
</configuration>

Step 3: Remember to go the demo.aspx page and remove the lines for control, which had the registration of the Example component. If you do not include this step, then the ExampleControl.ascx file will be executed from the demo.aspx file instead of web.config file.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx" Inherits="DemoApplication.Demo" %>
<%@ Register Src="~/ExampleControl.ascx" TagName="WebControl" TagPrefix="TWebControl"%>
<!DOCTYPE html>
<html xmlns="https://www.w3.ore/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
<form id="formSubmit" runat="server”>
  <TWebControl:WebControl ID="Header" runat="server" />
</form>
</body>
</html>

How to add properties to a web control?

The property contains a key-value pair that is associated with any control. Now take an example of the simple <div> HTML tag. 

Creating Asp.net Controls, Webforms and Web config file

The <div> tag creates a section in an HTML document. The <div> tag contains a property called style property used to give a different style to the text that is displayed in the <div> tag. 

Therefore, the color attribute is nothing but a key-value pair that gives more information on the tag itself. Here, the key name is style, and the key value is color:#0000FF.

Similarly, you can create your properties for user controls that describe the control.

For example, we are adding a simple integer property called MinValue that would represent the minimum number of characters in the text that is displayed in the user control.

Let us carry out the below-mentioned steps:

Step 1: Open the ExampleControl.ascx file and add the code for adding the MinValue property.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx" Inherits="DemoApplication.Demo" %>
<script runat="server">
  public int MinValue = 0;
</script>
<table>
<tr>
  <td> Tutorials</td>
</tr>
<tr>
  <td> This Tutorial is for Web Forms</td>
</tr>
</table>

Step 2: Now let us reference this property in our demo.aspx file by referencing the MinValue property and assign a new value of 100.

!DOCTYPE html>
<html xmlns="https://www.w3.ore/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
<form id="formSubmit" runat="server”>
  <TWebControl:WebControl ID="Header1" runat="server" MinValue="100"/>
</form>
</body>
</html>

What are the basic differences between adding web user control on each page and adding at web.config file?

Sometimes you might want to use user controls in multiple pages in a .Net application. At this point, you do not want to keep on registering user controls on every ASP.Net page and so you can create the registration in the web.config file.

Also, when declaring UserControls in the web.config file, the controls have to reside in a different directory than the page(s) using it.

In case of adding web user control on each page, if the same control is needed in more than one application, it creates redundancy and maintenance problems. But, in case of adding web user control at web.config, it does not create problems associated with redundancy and maintenance.

Adding web user control on each page is a much better choice when you need static content within a fixed layout, for example, when you make headers and footers. However, when an application requires dynamic content to be displayed and can be reused across an application, adding web user control at web.config is preferred.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class