Practical Approach of Creating User Control in ASP.NET


In this article we are going to see how to create a user control in ASP.NET.
 
Advantage of using a User Control

  1. The easiest way to combine several controls into a single control.
  2. Can simply be dragged onto a Web page without writing much code.
  3. Helps to reduce duplicate coding.
  4. Web pages can even be converted to user controls.
  5. User controls inherit from the UserControl class, which inherits from the Template-Control class, which inherits from the Control class.

Steps to Create User Control

1. Go to File -> New -> Project

img1.jpg

2. Type the required name for the user control and click Add Button.

img2.jpg

3. You will get the markup for SampleUserControl.ascx shown below.

<%@ Control Language="C#"

        AutoEventWireup="true"

        CodeBehind="SampleUserControl.ascx.cs"

        Inherits="UserControlSample.SampleUserControl" %>

4. You will get the code behind as following.

namespace UserControlSample

{

    public partial class SampleUserControl : System.Web.UI.UserControl

    {

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

    }

}

5. Now add you controls into the User controls. Controls like TextBox and Label show a simple example. Note Controls can be placed just below the Control directive.

img3.jpg

6. Register the User control in a web page. Use just next to page Directive.

<%@ Register

 Src="SampleUserControl.ascx"

 TagName="MyControl"

 TagPrefix="uc1" %>

Src - User Control page name with extension.
TagName - Tag name can be any name, this is user defined.
TagPrefix - Can be any prefix, this is user defined.

7. Register and add a user control in a web page then run the default.aspx page.

img4.jpg

8. Embedded output of web page:

img5.jpg

This is very useful for reducing duplicate code and helps to reuse the control and save time in retyping the code. 


Similar Articles