Tuesday, 24 June 2014

How to Set MaxLength property for ASP.NET Multiline Textbox

Once there was a requirement in a project where I had to set the max length of TextBox in Multiline mode so I just set the MaxLength property of TextBox to the length which was required but it doesn’t worked. When i Searched on this, i found that when we put TextBox in our WebForm it’ll be rendered to HTML <input> tag but when we set the TextMode to multiline it’ll be rendered to <textarea> tag not an <input > tag, and MaxLength attribute is in <input> but it’s not for <textarea>. That's why i had to face this problem. Finally, I solved this problem by making javascript function.

aspx page

<asp:TextBox ID="txtName" runat="server" TextMode="MultiLine" onkeypress="return SetMaxLength(this,10);">

javascript function

    // maxLength value supplied by user
      function SetMaxLength(txt, maxLength) {

          if (txt.value.length >= (maxLength)) {
                return false;
          }
          else {
                return true;
          }
      }
As you can see, i am passing 10 in it that's why it will make the max number of characters user can input in the TextBox is 10. You can set it to accrording to your requirement. That's it.. Hope it will help you..


That’s it!!…..Happy Programming...

No comments:

Post a Comment