Setting the Maximum Length of a Singleline/Multiline TextBox

How can I set the maximum length of a singleline/multiline textbox in a webform?

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:

function Count(text,long)

{

   var maxlength = new Number(long); // Change number to your max length.

   if (text.value.length > maxlength){

   text.value = text.value.substring(0,maxlength);

   alert(" Only " + long + " characters");

}

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:

<asp:TextBox ID="TESTDATA" runat="server" TextMode="MultiLine">asp:TextBox>

After adding the code:

<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