Wenn man eine ASP.NET Textbox im Textmode="Multiline" erstellt, funktioniert dummerweise Maxlength nicht, da die HTML-Textarea das nicht unterstützt.

Hier ist die passende Javascript-Function und der VB-Code dazu. 

Um das Feature später einfac h ändern zu können, suche ich erst alle Textboxen innerhalb eines Panels und aktiviere entsprechende onChange und onKeyDown Events.

 

    1     Sub setMaxlength()

    2         For Each ctl As Control In Panel1.Controls

    3             If ctl.GetType Is GetType(TextBox) Then

    4                 Dim myTextbox As TextBox = ctl

    5                 If myTextbox.TextMode = TextBoxMode.MultiLine _

    6                     AndAlso myTextbox.MaxLength > 0 Then

    7 

    8                     myTextbox.Attributes.Add("onChange", _

    9                                "checkMaxLength(this," & myTextbox.MaxLength & ",1)")

   10 

   11                     myTextbox.Attributes.Add("onKeyDown", _

   12                                "checkMaxLength(this," & myTextbox.MaxLength & ",0)")

   13 

   14                 End If

   15             End If

   16         Next

   17     End Sub

 

 

 

    1     <script type="text/javascript">

    2 

    3         function checkMaxLength(obj, maxLength, typ) {

    4             if (obj.value.length > maxLength) {

    5                 if (typ == 1) {

    6                     alert("Die Maximallänge dieses Feldes beträgt\n"

    7                             + maxLength +

    8                            " Zeichen.\n\nDer Text wird jetzt gekürzt.");

    9                 } else {

   10 

   11                 }

   12                 obj.value = obj.value.substr(0, maxLength)

   13             }

   14         }

   15     </script>