Creating a Custom Web Server Control


In this article we will focus on: 1. How to Create Custom Web Server Control. 2. Adding the Custom Web Server Control to the Toolbox and using this newly created Custom Web Server Control from the Toolbox. 3. Consuming Custom Web Server Controls in a Website.

In this article we will focus on:
1. How to Create Custom Web Server Control.
2. Adding the Custom Web Server Control to the Toolbox and using this newly created Custom Web Server Control from the Toolbox.
3. Consuming Custom Web Server Controls in a Website.

Why Custom Web Server Controls:
Easier to use than User Controls.
We can define a complete design time experience for the consumers of our Custom Web Server Control such as ToolBox support and designer functionality.
Only drawback is we will end up writing more code than the User Control code.
When to use Custom Web Server Control :
If you want to reuse a control across websites then go for Custom Web Server Control.

Creating a Custom Web Server Control:
1.A Custom Web Server Control is a control that inherits from either an existing Web Server control or from the WebControl class.
2.We can compile the control into a separate dll file that can be either be shared among applications or we can also deploy it into GAC.
3.There are two ways of creating a Create Custom Web Server Control :
a.Create a web server control that inherits from the WebControl class that provides a basic functionality. This way needs lot of work to develop this control.
b.Inherit from an existing Web Server control that provides the core features required for the control. Here we can focus on additional functionality required for the control.

In this article we will see both the approaches of creating a Web Server Control.
First Approach: Inheriting the Custom Web Server Control from an Existing ASP.NET Web Server Control.
Let us create a control that includes a Label and a TextBox. We will name this control as "UserCustomWebControl". User can set the Text of the Label which would label the TextBox(UserName and Password). We will allow the developer to set the text of the control(Label).

Step 1:
Open Microsoft Visual Studio -> Create a New Website ->Select Visual C# under Templates on the Left pane -> Select ASP.NET Web Forms Site -> name it "MyCustomControlDemo".
1
2
Step 2:Create Custom Web Server Control as a dll
Right Click the solution -> Add New Project -> Select "ClassLibrary" name it as: "MyCustomInputControl". Then Create a class "UserCustomWebControl" and add reference to System.Web assembly. ->Right click the "MyCustomInputControl" project and click on Add Reference-> Select System.Web and click on Ok. This adds reference to System.Web. Now add below namespace in the class
using System.Web.UI;
using System.Web.UI.WebControls;

3

8
Step 3:Inherit the class from the TextBox class.


public class UserCustomWebControl : TextBox

Step 4:Add the below two properties for Label Width and Label Text. As our custom control inherits from TextBox control, the TextBox properties are exposed by default.

public string LabelText { get; set; }
public int LabelWidth { get; set; }

Step 5:Overwrite the Render method to display the control
Render method uses the HtmlTextWriter to write the display of the UserControl and the base rendering of the TextBox control.

protected override void Render(HtmlTextWriter writer)
{
writer.Write(@"{1} ", LabelWidth, LabelText);
base.Render(writer);
}

Step 6:Build the Class Library and add its reference to our website so that we can use this server control on our webpage.
4
5

Step 7:Write the below code in Default.aspx.cs file

protected void Page_Init(object sender, EventArgs e)
{
ContentPlaceHolder content = (ContentPlaceHolder)this.Master.FindControl("MainContent");

UserCustomWebControl cWebControl = new UserCustomWebControl();
cWebControl.LabelText = "User Name";
cWebControl.LabelWidth = 100;
cWebControl.Width = 150;
content.Controls.Add(cWebControl);
LiteralControl br = new LiteralControl("
");
content.Controls.Add(br);

UserCustomWebControl cWebControl1 = new UserCustomWebControl();

cWebControl1.LabelText = "Password";
cWebControl1.LabelWidth = 100;
cWebControl1.TextMode = TextBoxMode.Password;
cWebControl1.Width = 150;

content.Controls.Add(cWebControl1);
}

In the above code we are writing code in the Page_Init event handler. Page_Init event is raised after all controls of the page have been initialized.
Since Default.aspx page uses a masterpage. First we will get referene to the ContentPlaceHolder "MainContent" in which all controls will be placed. Then we will create an instance of our Custom WebServer control "UserCustomWebControl" and then initialize its Label Text and Width properties Then we will add this custom web server control to the Controls collection of the ContentPlaceHolder.

Similarly we will create another instance of our Custom WebServer control "UserCustomWebControl" and then initialize its Label Text and Width properties Then we will add this custom web server control to the Controls collection of the ContentPlaceHolder. This time we will set the TextMode property of the Textbox to Password so that password is not visible in Text format. We will also set the Width of the TextBox to 150px. As you can see TextBox properties are available to us by default as our custom webserver control is inheriting from the TextBox class. We are also adding a newline after the first custom webserver control to display the second custom webserver control on the next line.

Step 8:Run the Website and see the output
Press Ctrl + F5 to build and run the website. You will see the output with the render Custom WebServer control.
6
Second Approach: Inheriting from the WebControl Class
When the behaviour we want to implement in a control is not already existing then we need to follow this approach. Here we have to create a class that inherits from WebControl class and override the Render method to provide the HTML output we need for our control. By Default Render method in turn calls the below methods in order:

RenderBeginTag:Used to render HTML at the beginning of the control.
RenderContent:Use this method to ensure that HTML of our control is rendered correctly between begin and end of the HTML tags.

RenderEndTag:Used to render HTML at the end of the control.

Let us create a custom control that allows a user to display
our web site logo and our website name. We will create two properties: WebsiteLogoUrl and WebsiteName. Then we will add code to render the output. In the below example, the RenderBeginTag and RenderContents methods are used to display the HTML for the control. Please note that RenderEndTag is not required, because it is automatically
called and will render an end tag based on the supplied begin tag.

Step1:Create a New ClassLibrary project
Create a Class Library project in the solution as shown above and name it "MyWebsiteLogoControl". Add reference to System.Web assembly in this class library.
7

Step 2:Create Custom WebServer control class
Create a class "SiteLogoControl" as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;

namespace MyWebsiteLogoControl
{
public class SiteLogoControl : WebControl
{
public string SiteLogoPath { get; set; }
public string SiteName { get; set; }

public override void RenderBeginTag(System.Web.UI.HtmlTextWriter writer)
{
writer.RenderBeginTag("div");
}

protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
writer.Write(@"<img src=""{0}"" alt=""Website Logo"" /><br>>", SiteLogoPath);
writer.Write(SiteName + "<br/>");
}
}
}

In the above code we are rendering image tag with the custom website logo(image)and site name in a div tag. The ending of the div tag is automatically rendered in the RenderEndTag event.


Step 4:Using Cusom Webserver control in our website
In the default.aspx page, Add the following register directive to register the custom webserver control as a dll file.

<%@ Register Assembly="MyWebsiteLogoControl" Namespace="MyWebsiteLogoControl" TagPrefix="muc" %>

Step 5 Use the Custom Webserver control and assign the values as shown below:

<muc:SiteLogoControl runat="server" SiteLogoPath="Images/logo.png" SiteName="DOT NET SPIDER" />


Run the application and you will see the output as shown below:
website usercontrol

Adding the Custom Web Server Control to the Toolbox
Go to Default.aspx page ->Open ToolBox window -> RightClick under "General" category and select "Choose Items" -> Click on Browse ->Navigate to the folder where our Custom Web server control(Class Library) dll file is present -> select the class library dll(MyCustomInputControl.dll) -> similarly select another custom webserver control dll(MyWebsiteLogoControl) we created above and click on ok. This adds both the custom controls to our ToolBox. I have demostrated all these steps in the below screens.

Right click on ToolBox and Select Choose Items
chooseitems
Now Select Browse to select the custom WebServer control dll file from the Debug folder of the Class Library project.
Browse
Navigate to the appropriate Folder
navigate root folder
Select the dll file
custom webserver control dll
The custom WebServer control gets added to the .NET Framework Components list as shown
list
Similary select other Custom WebServer control dll file
other dll
The second custom WebServer control gets added to the .NET Framework Components list as shown
second dll list

As you can see in the Below screen both the Custom WebServer controls as added to the ToolBox.Now Click on OK button.
AddToToolbox

Now we can Drag and Drop these controls in our Web Page and use them like any other Web Server Control. Isn't so easy to create a Custom Web Server Control?

Add a New WebForm"Default2.aspx" to the Website and Drag and drop the Custom Web Server controls to the web page and set its properties as shown below
Default2

The final output looks as below
output


Article by Vaishali Jain
Miss. Jain Microsoft Certified Technology Specialist in .Net(Windows and Web Based application development)

Follow Vaishali Jain or read 127 articles authored by Vaishali Jain

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: