Set the Maximum Length of a Singleline/ Multiline Textbox in a Web Form

Restricting the length of text on a Single line/Multi line textbox is not supported by the standard ASP.NET Web control. This can be done by adding the following Javascript function in your ASPX page.

  1. Add a javascript

    At the top of your ASPX page you will see the following tag . Add the following code under this tag,
    1. function Count(text, long)  
    2. {  
    3.     var maxlength = new Number(long); // Change number to your max length.  
    4.     if (text.value.length > maxlength) {  
    5.         text.value = text.value.substring(0, maxlength);  
    6.         alert(" Only " + long + " characters");  
    7.     }  
    8. }  
  2. Change your text controls on your ASPX page

    On every multi-line text box where you would like to control the length, add the following code to the asp text box control.

    onKeyUp="Count(this,300)" onChange="Count(this,300)"

    Your original text control before adding this code,
    1. <asp:TextBox ID="TESTDATA" runat="server" TextMode="MultiLine">asp:TextBox>   
    After adding the code
    1. <asp:TextBox ID="TextBox1" runat="server" onKeyUp="Count(this,300)" onChange="Count(this,300)" TextMode="MultiLine">asp:TextBox>  
Ebook Download
View all
Learn
View all