Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

TextBox Class - ASP.NET

RSS
Modified on Fri, Jan 07, 2011, 2:48 PM by Administrator Categorized as ASP·NET Web Forms, Class Library

Features

It is common knowledge — even documented on MSDN — that the standard ASP.NET TextBox control does not enforce its MaxLength property when its TextMode property is set to MultiLine. The TextBox class below overcomes that shortcoming.

See Also


Source Code

To use this control, follow the instructions in the Consuming Custom Controls in ASP.NET article.

VB.NET

Imports Microsoft.VisualBasic

Namespace AcmeBroomCompany
    Public Class TextBox
    Inherits System.Web.UI.WebControls.TextBox

        Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
            writer.Write(Me.Script)
            Dim s As String = "EnforceMaxLength(this, " & MyBase.MaxLength & " );"
            MyBase.Attributes.Add("onchange", s)
            MyBase.Attributes.Add("onkeyup", s)
            MyBase.Render(writer)
        End Sub

        Private Function Script() As String

            Dim s As StringBuilder = New StringBuilder()

            s.Append("<script language='javascript'>")
            s.Append("function EnforceMaxLength(textBox, maxLength) {")
            s.Append("    var x = new Number(maxLength);")
            s.Append("    if (textBox.value.length > x) ")
            s.Append("    {")
            s.Append("        textBox.value = textBox.value.substring(0, x);")
            s.Append("        return false;")
            s.Append("    }")
            s.Append("    return true;")
            s.Append("}")
            s.Append("</script>")
            Return s.ToString()

        End Function

    End Class
End Namespace

C#

TODO

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.