Microsoft



ISDV 165

Lecture #8: User, Custom and Composite Controls

2.0 provides a rich set of standard controls that help addressing the major needs in web applications. However, sometimes the functionality you are seeking is not provided and you will find your self developing your own web control. There are 3 mail types of custom controls: User, custom and composite.

User Controls:

User controls encapsulate common functionality in pages enabling us to package and reuse common content and programming logic.

Simply speaking, a user control is an page that is converted to a control. This means that user controls can contain any kind of content and can include server controls. User controls are stored in files with the extension .ascx.

User controls inherits from UserControl class which in turn inherits from TemplateControl. TemplateControl inherits from Control class.

We can create a user control in VS 2005 by creating a website and adding Web User Control as a new tem.

Once a user control is created, it can be used in an page just like any other server control. User controls are compiled and stored in the server memory the first time they get requested. They cannot be requested independently, but must be included in a web form page to work.

The @ Control directive is used to define a user control attributes. Some of these attributes are:

• AutoEventWireup: Indicates whether the page’s events are wired automatically , or it has to be done manually

• ClassName: Specify a class name to be dynamically compiled when the page is requested.

• CodeFile: Indicates the file name of the code behind class.

• CompilerOptions: String representing compilation options.

• Debug: Indicates whether the page is compiled with debug symbol or not.

• Description: Provides a text description for the page

• EnableSessionState: Defines session requirement for the page.

• Explicit: Indicates whether the page should be compiled using VB

• Inherits: Code behind class for page to inherit. Can be any class that inherits the Page class.

• Language: Language used to compile code render blocks ( and

• Strict: Indicates whether the page is compiled with strict mode or not

• Src: Defines the path for the code behind class to compile

• WarningLevel: level of warnings (0-4)

To add a user control to a page, we use the @Register directive. The @ Register directive is used to register the user control. Some of its attributes are:

• Tagprefix: An alias to associate with a namespace

• Tagname: An alias to associate with a class

• Namespace: The namespace to associate with the tagprefix.

• Src: The location of the user control associated with the Tagprefix:tagname

We can declaratively instantiate a custom control using the following syntax:

The following attributes can be used in the above tag:

• tagprefix: an alias for the fully qualified name namespace for the control

• tagname: the name of the class that encapsulate the control

• id: a unique identifier for the control

• attributename: the name of an attribute

• propertyname: the value assigned to attributename

• propertyname: the name of a property being defined

• suproprtyvalue: the value assigned to propertyname

• eventname:the event name of the control

• eventhandlermethod: the name of the event handler method

User controls can be customized by exposing public properties that can change their behavior and appearance.

Be default, the user control does not add an outer tag the expose the style attribute. This prevents us from positioning the user control using the absolute position. To overcome this limitation, we can place the control in a panel which expose the style attribute.

User controls can have event handling methods. The code of the event handling method is placed in the user control. If you need the page to handle a user control event, you must raise the event in the user control. Subroutines and functions can be exposed as methods of the user control. User controls can be created programmatically like any other server controls.

We can also convert existing web pages to user controls. To do this, perform the following:

• Remove html, body and form tags (beginning and end tags).

• Change @Page to @Control. In the Control directive, change Inherits=”System.Web.UI.Page” to Inherits=”System.Web.UI.UserCOntrol”

• Change the file extension from aspx to ascx

Custom Controls:

Custom controls enable us to extend the functionality of existing server control, or create new controls from scratch. We can also cerate a composite custom control by combining existing controls, which are knows as childControls.

Unlike user controls, custom controls are places usually in a class libraries and compiled into assemblies before they can be used and have visible user interfaces. Once created, they can be added to a toolbar of an IDE such as Visual 2005. However, the rendering in a custom control is controlled programmatically. The Control class is the primary class that must be inherited to create custom controls. Control does not have any user interface (UI) specific features. If you are authoring a control that does not have a UI, or combines other controls that render their own UI, derive from Control class. We can also inherit from the class System.Web.UI.WebControl. This class serves as the base class that defines the methods, properties and events common to all controls in the System.Web.UI.WebControls namespace. The primary benefit from inheriting from System.Web.UI.WebControls is styles.

Custom controls can be customized by exposing their properties that can change their behavior and appearance. Custom controls can have their own custom events. In order for a custom control to handle post back data processing, it must implements the System.Web.UI.IPostBackDatahandler interface. This interface defines two methods:

• LoadPostData: This method is invoked when the postback occurs and the control has postback data. This method has the following signature:

Function LoadPostData( ByVal postDataKey as String, ByVal postCollection as nameValueCollection) As Boolean

postDataKey is the unique name of the control. postCollection has access to all the postback data. This function should return true if you want to raise an event after the postback, otherwise it should return false.

• RaisePostDataChangedEvent: This function is called when the LoadPostData return true for a custom control.

Composite Control:

A composite control is a custom control that contains other constituent controls, added to its Controls collection and rendered as a tree. The composite control inherits from CompositeControl class and override CreateChildControls method. Each constituent control has its own life cycle and knows how to handle its events, ViewState and PostBack data.

Examples:

Ex1:

In this example we will create a simple user control to display a static header. The user control will be stored in the file WebUserControl.asax with the following content:

Hello from user control

In the following page, we will use our user control.

Simple user control example

Notice that the two files are stored in the same directory.

Ex2:

The user control in this example utilizes a label and button controls. The user control will expose some attributes for the label and have an event handler for the button control. First we will create the user interface for this control in a file called WebUserControl2.asax:

Next, we will create the code behind for the user control:

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Drawing;

public partial class WebUserControl2 : System.Web.UI.UserControl

{

private string labelText;

private Color labelColor;

protected void Page_Load(object sender, EventArgs e)

{

this.lblOutput.ForeColor = Color.Blue;

this.lblOutput.Text = LabelText;

}

public string Style

{

get { return Panel1.Attributes["style"]; }

set { Panel1.Attributes["style"] = value; }

}

public string LabelText

{

get { return labelText; }

set { labelText = value; }

}

public Color LabelColor

{

get { return labelColor; }

set { labelColor = value; }

}

protected void btnClick_Click(object sender, EventArgs e)

{

lblOutput.BackColor = LabelColor;

}

}

The following page will utilize the above user control:

Top of Form

Bottom of Form

Top of Form

Bottom of Form

Simple user control example

Ex3:

We can add user controls programmatically as we add any other build in control. In this example, we will create an page that adds the user control created in example 2 programmatically.

Following is the user interface for the page:

Top of Form

Bottom of Form

Adding user control programmatically

And following is the code behind for this control:

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Drawing;

public partial class ProgrammaticallyAddingUserControl : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

WebUserControl2 cnt = (WebUserControl2)LoadControl("WebUserControl2.ascx");

cnt.LabelText = "hello";

cnt.LabelColor = Color.Red;

this.form1.Controls.Add(cnt);

}

}

Ex4:

Instead of handling the button event in the user control, we will handle it in the page. First we will create the user interface for this control in a file called WebUserControl3.asax:

Below is the code behind for this control:

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Drawing;

public delegate void SendMessageFromButton(object s, EventArgs e);

public partial class WebUserControl3 : System.Web.UI.UserControl

{

private string labelText;

private Color labelColor;

public event SendMessageFromButton msgHandler;

protected void Page_Load(object sender, EventArgs e)

{

this.lblOutput.ForeColor = Color.Blue;

this.lblOutput.Text = LabelText;

}

public string Style

{

get { return Panel1.Attributes["style"]; }

set { Panel1.Attributes["style"] = value; }

}

public string LabelText

{

get { return labelText; }

set { labelText = value; }

}

public Color LabelColor

{

get { return labelColor; }

set { labelColor = value; }

}

protected void btnClick_Click(object sender, EventArgs e)

{

msgHandler(sender, e);

}

}

We will add this control to a page and handle its event. Following is the user interface:

Simple user control example

  

And here is the code behind for the page:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Drawing;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

this.WebUserControl3_1.LabelText = "hello";

this.WebUserControl3_1.LabelColor = Color.Red;

this.WebUserControl3_1.msgHandler+=new SendMessageFromButton(WebUserControl3_1_msgHandler);

}

public void WebUserControl3_1_msgHandler(object s, EventArgs e)

{

Response.Write("hello");

}

}

Ex5:

In this example, we will create a custom control that extends a TextBox web control. This control will allow users to enter numeric values only. We will use client side script to handle the javascript onkeypress event.

Create a new class library project called FirstCustomControl. Rename the class to FirstCustomControl:

using System;

using System.Collections.Generic;

using System.Text;

using System.Web.UI;

// you need to add a refernce to System.Web

using System.Web.UI.WebControls;

namespace FirstCustomControl

{

public class FirstCustomControl : TextBox

{

protected override void Render(HtmlTextWriter writer)

{

StringBuilder s = new StringBuilder();

s.Append("");

s.Append(" function validate(e) {");

s.Append(" var IsNumber=false; var key = document.all ? event.keyCode : e.which;");

s.Append(" if ((key >=48) && (key ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download