ARTICLE

Practical Approach of Creating User Control in ASP.NET

Posted by Lajapathy Arun Articles | ASP.NET Controls in C# April 08, 2012
In this article we are going to see how to create a user control in ASP.NET.
Reader Level:
Download Files:
 

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. 

Login to add your contents and source code to this article
post comment
     

nice and easy....

Posted by amandeep singh Sep 17, 2012

Hi, Arun It's a great effort and really very helpful for beginners, So keep it up and thanks for sharing.........

Posted by Amit Maheshwari Apr 09, 2012

Hi, This article is so good keep it up...

Posted by Jimmy Underwood Apr 08, 2012
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter