In this article we are going to see how to create a user control in ASP.NET.
Advantage of using a User Control
- The easiest way to combine several controls into a single control.
- Can simply be dragged onto a Web page without writing much code.
- Helps to reduce duplicate coding.
- Web pages can even be converted to user controls.
- 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
2. Type the required name for the user control and click Add Button.
3. You will get the markup for SampleUserControl.ascx shown below.
<%@ Control Language="C#"
4. You will get the code behind as following.
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.
6. Register the User control in a web page. Use just next to page Directive.
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.
8. Embedded output of web page:
This is very useful for reducing duplicate code and helps to reuse the control and save time in retyping the code.