Wednesday, September 26, 2007

Web User Control in Asp.Net

All About User Controls in .Net

Getting started with Web User Control in Asp.net and lets explain it easy step by step.

What is Web User Control?
A Web User Control, is a Web Form. You can say it as a web form, which can be placed on multiple web form and can be reused.

Example of Web User Control in Asp.Net
You can use Web User Control to create to display User Status. i.e. based on whether user is logged-in or not display him appropriate message. If use is logged-in display "Welcome UserName" And if not than display message "Welcome Guest". You will understand it more practically latter in this article.

Extension of Web User Control in Asp.net
UI File: .ascx (Like Web form Compiled First time when WebPage is requested.)
Class File: .ascx.cs (Like Component Precompiled File, so it can improve performance)

Difference between Web Form and Web User Control
User Control are used within Web Form and do not contain the following HTML Tags.

  • <Head> Tag
  • <Body> Tag
  • <Form> Tag

Creating Web User Control in Asp.net
We are going to create a simple ImageViewer Control, which display thumnail view of image and on clicking "Original View" under it will redirect you to original view of Image. Practically it has is scrap, but I have used here so that example remain simple throughout the discussion.

Step1: Create Asp.net Website Project

Step2: Add User Control as shown in figure.



Select "Web User Control" from New Item Window and name it "ucImageViewer"




Step3: Now Add following code to file .ascx

Here it Adds a Image Server Control and Place a Button control below it. To organize properly it has displayed in table.

<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="ucImageViewer.ascx.cs" Inherits="ucImageViewer" %>

<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<asp:Image ID="Image1" runat="server" />
</td>
</tr>
<tr>
<td align="center">
<asp:Button ID="Button1" runat="server" Text="Original View"
OnClick="Button1_Click" />
</td>
</tr>
</table>


Step4: Now as we want to view "Original View" of Image, we need to write a code on button click control, so for that switch to code view i.e. open .ascx.cs file and add following code.

protected void Button1_Click(object sender, EventArgs e)
{
if (ImagePath == string.Empty)
return;
else
Response.Redirect(ImagePath);
}


Step5: Adding public property to Web User Control
Note, here you can access the Image Control property within User Control, but it won't be available when you place user control on web form, so to make desired ImageControl property accessible you need to define public property.

public string ImagePath
{
get
{
return m_ImagePath;
}
set
{
m_ImagePath = value;
}
}

public string ImageName
{
get
{
return m_ImageName;
}
set
{
m_ImageName = value;
}
}

public int ImageHeight
{
get
{
return m_ImageHeight;
}
set
{
m_ImageHeight = value;
}
}

public int ImageWidth
{
get
{
return m_ImageWidth;
}
set
{
m_ImageWidth = value;
}
}

So we are done forming Web User Control, now its turn to render Web User Control on Web Form.


Displaying Web User Control on Web Form in asp.net
To display web user control you can simply drag the user control on to web form as you are dragging web server control.

Lets understand manually how we can add the Web User Control on Web Form

Step1: Add Register directive
Like <%@ Page %> directive, you can create Register directive

<%@ Register Src="ucImageViewer.ascx" TagName="ImageViewer" TagPrefix="uc" %>

Understanding Attributes of Register directive

Src - It specifies source of web user control.
TagPrefix - It Specifies Prefix for user control, i.e. Namespace to which it belong.
TagName - It Specifies Alias to the user control. i.e. Id to Control.

Now, you need to add the control
<uc:ImageViewer ID="ImageViewer1" runat="server" />

Note: As we have form public property with Web User Control, we can access
ImagePath - To Specify path of Image.
ImageName - To display Image Name as alternate text.
ImageHeight
ImageWidth

Example:

protected void Page_Load(object sender, EventArgs e)
{
ImageViewer1.ImagePath = "Image/shriganesh1.jpg";
ImageViewer1.ImageName = "Shri Ganesh 1st Pic";
ImageViewer1.ImageHeight = 200;
ImageViewer1.ImageWidth = 200;
}

Displaying Output of Web User Control Rendering


After clicking button, it display Image Original View as shown in figure.




Now, lets understand how to load user control dynamically.

Dynamically Loading of User Control in asp.net

protected void Page_Load(object sender, EventArgs e)
{
Control c = Page.LoadControl("ucImageViewer.ascx");

((ucImageViewer)c).ImagePath = "Image/shriganesh1.jpg";
((ucImageViewer)c).ImageName = "Shri Ganesh Pic";
((ucImageViewer)c).ImageHeight = 150;
((ucImageViewer)c).ImageWidth = 150;

Panel1.Controls.Add(c);
}


Creating a Web User Control from Existing Web Form in Asp.net
Step1: Remove all <HTML>, <Body> and <Form> Tags.

Step2: Change the @Page directive to a @Control directive and ensures that no unsupported attributes remain.

Step3: Add a ClassName attribute to the @Control directive.

Step4: Rename the file to a name that reflects its purpose and then change the file extension from .aspx to .ascx.


Overview of Web Custom Control
Web Cutsom Controls provides more flexibility as compare to web user control. With Web Custom Control you can provide
  • Design-Time Support
  • Data Binding
  • Event Handling and more advance feature.

Different ways to create web custom control
There are 3 different ways of creating a web custom control
  1. Composite Control - By combining two or more controls.
  2. Derived Control - By Inheriting from a server control.
  3. From Scratch - By Inheriting from the generic System.Web.UI.Control class.

Composite Control - Web Custom Control
A composite control is a web custom control composed of two or more standard web server controls. Composite controls are useful when you have group of controls that must be repeated consistently on the UI of an application.

Derived Control - Web Custom Control
Derive Control are web custom control created by inheriting a web server control. Derived controls are useful when you want to enhance the existing server control.

Control from Scratch - Web Custom Control
You can create a control from scratch by deriving it from System.Web.UI.Control class and writing code to handle the rendering and other task. It is useful when you want most flexibility and control over the generated HTML.


Web User Control Vs Web Custom Control
Difference between Web User Control and Web Custom Control or Points to be consider while Choosing Web User Control or Web Custom Control
  • Web User Control can only be used within the same project, while Web Custom Control can be used across many projects.
  • Web User Control cannot be added to Visual Studio.Net Toolbox, while Web Custom Control can be added.
  • Web Custom Control are better choice when you want dynamic layout tasks in which constituent controls must be created at runtime.

Facts about Web User Control in asp.net
  • When you include a web user control in a web form, the user control participates in the event life cycle for the web form.
    • User control Load and PreRender events are fired only after the web form's load and PreRender events are fired respectively.
  • Web User controls are not precompiled into assemblies like the components and custome controls, they can only be used in web applications that have a physical copy of the user control. Thus, every application that wants to use a user control should have its own copy of that user control.
  • Web User Control cannot be added into Visual Studio.Net Toolbox
  • Web User Control do not expose their properties through the properties window
  • Web User Controls in asp.net are Language neutral, that is user control written in C# can be used on a web form that is written in VB.Net.

Releated Link
Component Creation in .Net

3 comments:

Bhaskara said...

nice article to give an idea about user control.Thanks allot for this
http://csharpektroncmssql.blogspot.com

Parminder said...

Hi,
Nice article but when i tried to give a path, it didn't work. don't you think we have to map ImagePath property with ImageUrl?
Hope for an instant help. appreciated.

Santhosh.M said...

thanx for easy manner to undertand the topics.....nice
site

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape