MaxLength="Int32"
<asp:TextBox ID="txtBodySMS" runat="server" Rows="10" MaxLength="220"
TextMode="MultiLine" Width="100%"></asp:TextBox>
<asp:TextBox ID="txtBodySMS" runat="server" Rows="10" MaxLength="220"
TextMode="MultiLine" Width="100%">
</asp:TextBox>
AFAIK maxlength has never worked in conjunction with the "multiline" mode. Therefore I would suggest some client-side js/jquery and server-side to get around the problem.
Set the MaxLength attribute to the number of characters.
It seems to be a curious oversight in the design of ASP.NET (leaving aside the anomaly with textareas) that you can set the MaxLength property of a textbox but there seems to be no way provided to enforce this limit server-side without explicitly adding a validator. That's a nuisance if you have lots of fields and just want to be sure that no-one is subventing the limits of the form by injecting their own POST data. So I wrote this, which seems to do the trick - obviously you might not want to force Response.End
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim colControls As Collection = New Collection
getControlList(colControls, Me)
For Each ctlNextPlease As Control In colControls
If TypeOf (ctlNextPlease) Is TextBox Then
Dim ctlTextBox As TextBox = ctlNextPlease
If Len(Request(ctlTextBox.ID)) > ctlTextBox.MaxLength Then
Response.Write("The value <i>" & Request(ctlTextBox.ID) & "</i> submitted for <b>" & ctlTextBox.ID & "</b> exceeds the permitted maximum length (" & ctlTextBox.MaxLength & ") for that value")
Response.End()
End If
End If
Next
...
End Sub
Public Shared Sub getControlList(ByRef colControls As Collection, ByVal rootControl As Control)
colControls.Add(rootControl)
If rootControl.Controls.Count > 0 Then
For Each controlToSearch As Control In rootControl.Controls
getControlList(colControls, controlToSearch)
Next
End If
End Sub
It is important to note that using MaxLength
alone (with no other properties to add, just like the other answers) works ONLY for projects in .NET Framework 4.5 and above.
I'm using 4.5, and it worked for my project
<asp:TextBox ID="txtSample" MaxLength="3" runat="server"/>
TextBox.MaxLength Property (MSDN Documentation)