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. namespace Maxlength
  4. {
  5. public partial class MacLength : System.Web.UI.Page
  6. {
  7. protected void Page_Load(object sender, EventArgs e)
  8. {
  9. if (!Page.IsPostBack)
  10. {
  11. txtMultiLine.Attributes.Add("maxlength", txtMultiLine.MaxLength.ToString());
  12. }
  13. }
  14. }
  15. }
I hope you enjoyed it. Please provide your valuable suggestions and feedback.