Set MaxLength property to Multiline Textbox

It is so easy to limit the number of characters allowed in a normal textbox by using MaxLength property, But same doesn’t work if the TextMode property of textbox is set to Multiline.

By default TextMode = "SingleLine" for a normal textbox, and it gets rendered as an input type textbox and when we set its TextMode property to MultiLine, it gets rendered as a textarea.

code

Note: MaxLength property works only for input type and not for textarea. So to handle this, either you can use JavaScript, jQuery or any other scripts. But in this article I used C# to handle this.

So let's take an example, and take one normal textbox and one multiline textbox and see differences before and after writing codebehind.

.aspx:

  1. <asp:TextBox ID="txtMultiLine" runat="server" TextMode="MultiLine" MaxLength="5"></asp:TextBox>    
  2.         <br />    
  3.  <asp:TextBox ID="txtNormal" runat="server" MaxLength="5"></asp:TextBox>    
CodeBehind:
  1. using System;    
  2. using System.Web.UI;    
  3.     
  4. namespace Maxlength    
  5. {    
  6.     public partial class MacLength : System.Web.UI.Page    
  7.     {    
  8.         protected void Page_Load(object sender, EventArgs e)    
  9.         {    
  10.             if (!Page.IsPostBack)    
  11.             {    
  12.                 txtMultiLine.Attributes.Add("maxlength", txtMultiLine.MaxLength.ToString());    
  13.             }    
  14.         }    
  15.     }    
  16. }  
I hope you enjoyed it. Please provide your valuable suggestions and feedback.

 

Next Recommended Reading Shortcut Trick For Get & Set Property