See

Tuesday, November 27, 2007

USER control in Asp.net 2.0

User Control:
As the name suggest user control are made by developer based on there requirement which are not available. In single word you can say user control is customized control based on user requirement.
Many time webpage contains similar controls eg. Address it may be billing address or shipping address, or there are many other case of using similar controls. You can create a user control containing the name, address, city, state, and zip code and drop it onto a Web page where needed . It will save time and provide consistency in form of appearance.
There are two way for making User control
1. Using web userControl.ascx
2. Converting A standard Asp.net web page into User control page.

You can create a user control in Visual Studio 2005 by choosing Website, Add New Item, Web User Control
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="MyControl.ascx.cs" Inherits="MyControl" %>
It has .ascx extension making sure that it cannot executed standalone. I mean you have to use .aspx page to use the user control. All other control will same as on .aspx page.

Converting .aspx page to uaser control

Remove the , , and
begin and end tags.
Replace the @Page directive at the top of the file to an @Control directive.
In the @Control directive, change Inherits="System.Web.UI.Page" to Inherits="System.Web.UI.UserControl".
Save the page as .ascx instead of .aspx.
Adding user control to Asp.net page
It very simple to add a user control to a web page just drags and drops the user control to web page. It will rendered in .aspx page as given below



You can also use the properties in user control and access them Asp.net web page. Uneed to set the proprities in code behind file of usercontrol.
Dynamically laoding user control.

UserControl c1 =
(UserControl)LoadControl("UserControl.ascx");
c1.UserName = "ABC";
form1.Controls.Add(c1);

The LoadControl method loads the control into memory, but this method returns a System.Web.UI.Control. To see the properties of UserControl, the returned Control object must be cast as a UserControl object. The user control contains server controls, so it must be loaded into the controls collection of the form as shown.

Benefits of user control:
1. Easy to use
2. More efficient, required less development and testing time.
3. Less error prone.

No comments: