Search This Blog

Friday, September 10, 2010

Creating a custom control

Go to Projects and click on Add new project = Select ASP.NET server Control and give it a name, say, myCustomControl

A class is created which inherits WebControl. Here u can write methods and set properties. Properties are set in ViewState as their value might get lost between postbacks otherwise.

public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["Text"] = value;
}
}
 
You can access the public properties and methods in ur project (will see later).
Now build this application, so a dll is available to u
 
To add custom control to Project
The dll of myCustomControl must be present in bin folder. (use addExistingItem)
Then u need to register the Custom Control like this
<%@ Register Assembly="myCustomControl" namespace="myCustomControl" TagPrefix="myCC"/>
 
To use the customcontrol in aspx
<myCC:ServerControl1 ID="CC1" runat="server" /> (you can specify height width etc
 
To use it in codebehind, just use like any other server control
CC1.Text or any other property or method.

No comments:

Post a Comment