TextBox Class - ASP.NET

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