Introduction
This article explains and illustrates how the standard functionality provided by the Web Controls can be extended in order to fit the requirements of an individual or enterprise.
Background
I was working on a project that deals with the migration of an existing Power Builder application to .NET. Our natural choice for the new platform was .NET, the reasons being availability of developers and overall enterprise move towards a universal Microsoft shop. I came across a functionality in the existing app (Client/Server) where the user double clicks on a text box (date field) and the current date is inserted. In order to replicate this piece of functionality, we had write some JavaScript snippets in each page. Then we thought it is a painful process and hence we decided to come up with a control that extends the existing functionality of a textbox. It could be done with a user control as well, but we thought it might be useful to come up with a Web Control instead, so that this can be used in other projects as well.
Using the code
Download the source code. The download zip file contains a solution with the source code for both the control as well as the sample aspx page that includes the control. The code is given below:
VenusDateTextBox.vb
Option Strict On
Imports System.ComponentModel
Imports System.Web.UI
<DEFAULTPROPERTY("Text"), VALIDATIONPROPERTY("Text"),
TOOLBOXDATA("<{0}:VenusDateTextBox runat="server">")>
Public Class VenusDateTextBox _
Inherits System.Web.UI.WebControls.TextBox _
Implements INamingContainer
#Region " Member Variables "
Private Const DateIncludeScriptKey As String = "DateCurrentDateInsertScript"
Private Const DateCurrentDateInsertScript As String = ControlChars.CrLf & _
"<SCRIPT LANGUAGE=""JAVASCRIPT"">" & ControlChars.CrLf & _
"<!--" & ControlChars.CrLf & _
"function InsertCurrentDate(VenusDateControl)" & ControlChars.CrLf & _
" {" & ControlChars.CrLf & _
" var curDate = new Date();" & ControlChars.CrLf & _
" var formattedDate = curDate.getMonth() + '/'" & _
" + curDate.getDate() + '/' + curDate.getFullYear();" _
& ControlChars.CrLf & _
" document.all.item(VenusDateControl).value = formattedDate;" _
& ControlChars.CrLf & _
" }" & ControlChars.CrLf & _
"// -->" & ControlChars.CrLf & _
"</SCRIPT>"
#End Region
#Region " Overrides "
Protected Overrides Sub AddAttributesToRender(ByVal_
writer As System.Web.UI.HtmlTextWriter)
MyBase.AddAttributesToRender(writer)
writer.AddAttribute("ondblclick", _
"InsertCurrentDate('" & ClientID & "');")
End Sub
Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
MyBase.OnPreRender(e)
RegisterVenusDateIncludeScript()
End Sub
#End Region
#Region " Private Methods "
Private Sub RegisterVenusDateIncludeScript()
Dim location As String = Nothing
If Not Page.IsClientScriptBlockRegistered(DateIncludeScriptKey) Then
Page.RegisterClientScriptBlock(DateIncludeScriptKey,_
DateCurrentDateInsertScript)
End If
End Sub
#End Region
End Class