How to count character of TextBox in ASP.NET

Introduction

 
Here, we will see how to check the number of character has been inserted in the TextBox. A TextBox Which has max length 120 character and we insert a character in TextBox max length will be display 119 characters. When We enter 120 characters in the TextBox that will be the Max length. 
 
Drag and drop a TextBox on the page. Select TextBox and press F4 to the property window.
  1. TextMode="MultiLine" 
Now add the following code in the Head section of the .aspx page.
  1. <head runat="server">  
  2.     <title></title>  
  3.     <style type="text/css">   
  4.     .valid   
  5.     {  
  6.         background-color: #FFFFFF;  
  7.         color: #000000;  
  8.     }  
  9.     .invalid   
  10.     {  
  11.         background-color: #FFCCCC;  
  12.         color: #ff0000;  
  13.     }  
  14.     </style>  
  15.     <script language="javascript">   
  16.     function textCounter1(field, maxlimit)   
  17.     {  
  18.         if (field.value.length > maxlimit)   
  19.         {  
  20.             field.value = field.value.substring(0, maxlimit);  
  21.             document.getElementById('message').className = "invalid";  
  22.             document.getElementById('message').focus(); //alert('You have reached your maximum character limit.');}  
  23.         else   
  24.         {  
  25.             document.getElementById('message').className = "valid";  
  26.         }  
  27.     }  
  28.   
  29.     function textCounter(field, countfield, maxlimit)   
  30.     {  
  31.         if (field.value.length > maxlimit) // if too long...trim it!   
  32.             field.value = field.value.substring(0, maxlimit);  
  33.         else   
  34.             countfield.value = maxlimit - field.value.length;  
  35.     }  
  36.     </script>  
  37. </head> 
Now add the following code in the body section.
  1. <body bgcolor="#FFFFFF">  
  2.     <form name="blah" action="" method="post" runat="server">  
  3.            
  4.         <asp:TextBox ID="message" runat="server" name="message" onkeydown="textCounter(this.form.message,this.form.remLen,120)" onkeyup="textCounter1(this.form.message, 120)" class="validentry" Height="101px" TextMode="MultiLine" Width="228px"></asp:TextBox>  
  5.         <br/>   
  6.     <input readonly type="text" name="remLen" size="3" maxlength="3" value="120" position: absolute; style="width: 34px">Character left  
  7.     <br/>   
  8.     <br/>   
  9.     <br/>   
  10.     </form>  
  11. </body> 
Now run the application and check number of character has been inserted in the TextBox.
 
text1.gif
 
Figure1
 
Now Insert max length characters in TextBox.
 
text2.gif
 
Figure2