Saturday, July 19, 2008

Creating Custom Controls in ASP .Net

Creating Custom Controls in ASP .Net

In this article I have simply demonstrated 2 code examples for creating Custom Web Controls.

Why Custom Controls?
To cater through the real world scenarios that may not be supplemented by inbuilt .Net controls, the need for Custom Control arises. Also their are several other reasons for creating custom control like reusability, centralized management over the control, ease of usage etc.

How to approach the requirement for creating Custom Controls?
If any of the inbuilt .Net control meets your requirement than you should always use these controls. If not than ask yourself a question

Would any of the existing control help me?

If yes than
Inherit from the existing control and add the new features to it and extend it further.
If No than
You need to build the control from scratch. In this case inherit from WebControl class.

 

How to create Custom Controls?

Their are two ways in which you can create a custom control.
1) You can inherit from existing .net web control to extend its features further. OR
2) You can directly inherit from WebControl class to create a web control from scratch.

Depending upon the approach you choose their will be several properties and methods for you to override. All of them cannot be explained here so I am explaining some important among them that I have used in my code samples.

AddAttributesToRender - Adds HTML or Style attributes for any of your HtmlTextWriterTag. You can also use HtmlTextWriter's "AddAttribute" , "AddStyleAttribute" methods to achieve the same functionality. Make sure that you add this attributes before using "RenderBeginTag" method.

RenderContents - Outputs HTML content of Server Control to HtmlTextWriter object. So override this method to manage the HTML that your custom control renders to the browser.

TagKey - WebControl renders a span TAG by default on the cient browser. But to render any specific TAG you need to override this method.

Inheriting from the existing control
This example depicts the creation of a new web control named "myButton" that is derived from the Button class. It has all the features that a normal button control has. But for a twist I have added a simple feature that prompts for a message before submitting the page back to the server. I have added a new property called "AlertMessage" to quench this requirement.

[sourcecode language='csharp']

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace myControlLib
{
public class myButton : Button
{
public myButton() { }
private string _AlertMessage = "Are you sure to process this request!";
public string AlertMessage
{
set { _AlertMessage = value; }
get { return _AlertMessage; }
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "return confirm('" + _AlertMessage + "')"); base.AddAttributesToRender(writer);
}
}
}

[/sourcecode]

Registering the control on the web page

[sourcecode language='html']

<%@ Register Assembly="myControlLib" Namespace="myControlLib" TagPrefix="myUcl" %>

[/sourcecode]

Using the control

[sourcecode language='html']





[/sourcecode]





Inheriting from the WebControl class
This example depicts the creation of a new web control named "myImage" that is directly derived from the WebControl class. This control renders a Picture, Name of the Picture and Description of the Picture. Description of the Picture is displayed when the mouse is moved over the picture.
For this I have created 3 additional properties for this.

ImageUrl - The url of the image to be displayed

ImageName - The name of the image.

ImageDescription - The description for the image.

[sourcecode language='csharp']

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace myControlLib
{
public class myImage : WebControl
{
public myImage() { }

private string _ImageUrl = "";
public string ImageUrl
{
get { return _ImageUrl; }
set { _ImageUrl = value; }
}
private string _ImageName = "";
public string ImageName
{
get { return _ImageName; }
set { _ImageName = value; }
}
private string _ImageDescription = "";
public string ImageDescription
{
get { return _ImageDescription; }
set { _ImageDescription = value; }
}
protected override void RenderContents(HtmlTextWriter writer)
{
writer.AddAttribute("onmousemove", "javascript:document.getElementById('" + this.UniqueID + "_divDescription').style.display='';");
writer.AddAttribute("onmouseout", "javascript:document.getElementById('" + this.UniqueID + "_divDescription').style.display='none';");
writer.AddAttribute(HtmlTextWriterAttribute.Src, _ImageUrl);
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Div);
writer.Write("Name : " + _ImageName);
writer.RenderEndTag();
writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none");
writer.AddAttribute(HtmlTextWriterAttribute.Id, this.UniqueID + "_divDescription");
writer.RenderBeginTag(HtmlTextWriterTag.Div);
writer.Write("Description : " + _ImageDescription);
writer.RenderEndTag();
base.RenderContents(writer);
}
protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}
}
}

[/sourcecode]

Registering the control on the web page

[sourcecode language='html']

<%@ Register Assembly="myControlLib" Namespace="myControlLib" TagPrefix="myUcl" %>

[/sourcecode]

Using the control

[sourcecode language='html']

ImageDescription="My Image Description........" />

[/sourcecode]

Note: The above examples are the simplest controls that one can create. Remember that you can create more complex controls using the same approach. Choosing the best control that can serve the purpose of the requirement is our JOB and so make this decision very carefully.

How to make better appearance of your custom control in Visual Studio.

How to add custom control in Visual Studio Toolbox.

10 comments:

uday said...

Hi,

It works wrongly if i use validators like in the below example. myButton is a custom control created by you.when i use validators and on click of custom button,i shouldn't get alert message ,validators should work first and if validation success then only i should see confirm dialog box.Can you please tell me how it can be done.


UserName :




Password :

uday said...

UserName :




Password :

uday said...

i am using in-built validators in WEBForm.aspx and custom button control with no validators

2010 in review « Dhaval Upadhyaya said...

[...] Creating Custom Controls in ASP .Net July 2008 4 [...]

Malkesh Mistry said...

Hi Can I knew how to set Height / Width on the control.

4 said...

5

ravi patel said...

Error:Could not load file or assembly 'myControlLib' or one of its dependencies. The system cannot find the file specified. when i apply your image custom user control

Dustin said...

hello!,I love your writing very a lot! percentage we communicate extra about your article on AOL?

I require an expert in this house to unravel my problem. May be that's you! Looking forward to peer you.

Patricia said...

I really like your blog.. very nice colors & theme.
Did you create this website yourself or did you hire someone
to do it for you? Plz respond as I'm looking to design my own blog and would like to know where u got this from. thanks

hosen herren said...

If some one wants to be updated with newest technologies then he must be visit
this web page and be up to date daily.