Virtual Classes Logo          Virtual Classes
    Read Anytime,Anywhere


User Controls

A user control is a kind of composite control which is same as a ASP.NET Web page. Although ASP.NET has provided Web controls but some time you come across a situation where web server controls is not enough to full fill your application requirements. so .net has provided the feature to create user control which is the combination of more then one web controls. The main benifit of using user control is reusability.
We can create a user control and use it where ever it is needed, you don't have to write the same logic again.
To use a user control, you include it in an ASP.NET Web page. When a request arrives for a page and that page contains a user control, the user control goes through all of the processing stages that any ASP.NET server control performs.
How to create a user control-
Goto solution explorer--> right click--> choose add new iteam a dialog box will get open.Choose user control from the template list.

adding a User Control example

Give a name to your user control and click add. Once you click on add a file with extension ascx get added to your application.
Below image shows the HTML layout of user control. In my example I have added three controls to my user control.
User Control code example



Below image shows the use of created user control.
To use a user control first you have to register it to your web page. after registering it you can use it the same way you use the controls.
using a User Control in page example

A TagPrefix attribute, which associates a prefix with the user control. This prefix will be included in opening tag of the user control element.
A TagName attribute, which associates a name with the user control. This name will be included in the opening tag of the user control element.
A Src attribute, which defines the virtual path to the user control file that you are including.
The Src attribute value can be either a relative or an absolute path to the user control source file from your application's root directory. For flexibility, it is recommended you use a relative path. The tilde (~) character represents the root directory of the application.
User controls cannot be located in the App_Code directory.