Tips/Tricks - How to control MaxLength of Multiline TextBox in ASP.NET 1.1?
Problem : The users can enter as much charaters as he wants in Multiline Textbox even MaxLength of this textbox is set to a particular value. Obviously, this is a bug of ASP.NET.
Details of problem : When the TextMode property of textbox is set to Multiline, the MaxLength property wont be handled in controlling the maximum length of users inputs.

Steps to reproduce this issue (for those who doesn’t know that problem)
- Download Sample file
- Set “Problem.aspx” page as a startup page (There are two textboxes in this page. One is Multiline textbox (TextBox1.TextMode = Multiline) and another textbox is singleline textbox (TextBox2.TextMode = SingleLine). The MaxLength of Both textboxes are 10. )
- Run the project
- Type something more than 10 characters in both textboxes
Observe: You can type as many characters as you wants in TextBox1 (1st Textbox) but not in Textbox2 (2nd Textbox)
Solution ~
This problem can be solved by using Javascript to track how many characters typed in textbox. If the length of characters are over limited number (max number) then we can simply ignore what the user type by returning “false” in javascript function.
Step #1. Put the following function in your page.
<script language="javascript">
function textboxMultilineMaxNumber(txt,maxLen){
try{
if(txt.value.length > (maxLen-1))return false;
}catch(e){
}
}
</script>
Step #2. Put the JS function in onkeypress event of Textbox.
<asp:textbox id="TextBox1" runat="server" Width="232px" TextMode="MultiLine" Height="48px" style="Z-INDEX: 104; LEFT: 136px; TOP: 336px" onkeypress=<strong>"return textboxMultilineMaxNumber(this,10)"</strong>></asp:textbox>
Run the sample
- Set “Solution.aspx” as startpage in the demo project that you just download.
- Run the project
- Type something more than 10 characters
Observe: Both textboxes won’t let you type if the characters that you type are more than 10 as its defined.



