Sunday, October 5, 2008

How to use web cntrol library?

Web control library is a project which is help full for developer to build his custom controls like drop down list, grid view etc…
Please refer earlier blog regarding custom controls.

To add a web control library









Right click on your solution and click on add new project.
In new project template you can find “WebControlLibrary” under windows tab.


Building this web control library project creates .dll file which can be used in a web application by adding this dll as reference.

I shall build a Web control which shall render a html button onto browser.
Upon clicking on the button available in UI it displays the current date with an alert box.

Code :

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

namespace MyControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]
public class MyControl1 : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]

protected override void RenderContents(HtmlTextWriter output)
{
//This function is called by web server when an instance is created for this web control.
So this function is basically to prepare html content that can be rendered on to browser upon adding to this output HtmlTextWriter.
//Here I am writing a input button tag and java script click to it to display current date.
string strResponse = "<input type='button' value='What is todays date?' id='btnDate' onclick='var dt=new Date();alert(dt);'/>";
output.Write(strResponse);
}
}
}

After writing the web control code I shall build the web control library project .
After successful build I shall add refernce to web site under projects tab.









After adding the reference I shall open Test.aspx page in desing view of which I can find the “MyControl1” under mycontrol components tab,












As soon as I drag and drop that “MyControl1” the aspx page automatically registers that dll and I can use it as a normal web control.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<%@ Register Assembly="MyControls" Namespace="MyControls" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:MyControl1 runat="server">
</cc1:MyControl1>
</div>
</form>
</body>
</html>

Now upon running the application.












So I am using my custom build button control which shall display current date. So when ever I do applications that need this functionality I shall add this web control reference and re use it instead of re building the functionality.

No comments: