Posted by: savagerider | August 26, 2007

Creating User Control

To promote reusability of code and UI, we could create our own custom user control (.ascx).

User control can never request independently as asp.net page. It must use together with web form.

User control does not contain <html>, <body>, <form>. As these tags are needed for web form.

User control is neither custom server control nor web custom control.

Just like normal web form, which contains the code-behind page. In this case, user control makes use of “<@ control > ” tag to indicate the properties of it. This is similar to @ page in web form. Control tag does not support TRACE and ASPCompat !!!

<%@ Control Language=”c#” AutoEventWireup=”false” Codebehind=”WebUserControl1.ascx.cs” Inherits=”WebApplication1.WebUserControl1″> 

User control normally used as headers, navigation bars and repeating blocks of code.

User control uses its own namespace, this ensures no conflict on the variables and methods. It has its own postBack and control component.

User control can be written in different language from the hosting page.

To use user control in hosting page. Firstly, we need the following code on the top of .aspx

<%@ Register TagPrefix=”uc1″ TagName=”WebUserControl1″ Src=”WebUserControl1.ascx” %>

TagPrefix is the unique namespace

TagName is the unique name for the user control

Src is the file name of the user control

We add the user control with the following code:

<uc1:webusercontrol1 id=”WebUserControl11″ runat=”server”> 

 uc1 is the tagPrefix, webusercontrol1 is the tagName, id is used for behind-code.

To interact with the user control in behind-code, user control should expose control property on the user control page to hosting page. With this, the hosting page can access to the user control. Adding the following code to create a user control object [tagName].

protected WebUserControl1 WebUserControl11;

WebUserControl11.XXXX can access to the user control elements.

Two ways to create User Controls :

1. Create New User controls using visual studio .NET

2. Convert asp.net page to user controls (.ascx)


Leave a response

Your response:

Categories