Our Blog

ASP.NET MultiLine TextBox Length Property Problem And The Easiest Solution

In this article i will try to explain the problem when using the textBox as Multiline and set the MaxLength property , then the MaxLength property did not work. When an ASP.NET TextBox control is set to MultiLine mode, it is rendered as a TextArea HTML element. Sound like the TextArea element do not support 'MaxLength' attribute, and therefore the TextBox won't render this attribute in MultiLine mode. It won't give you any warning or throw an error, but quietly ignore this property.

For the example i have created a TextBox and set the TextMode to the MultiLine and also set the MaxLength of the TextBox to 5 character.

<asp:TextBox ID="TextBox2" runat="server" MaxLength="5" TextMode="MultiLine"></asp:TextBox>

Problem:

When you see the generated html of the page, you can see clearly that there is not MaxLength property for the TextBox. You can see that other properties are rendered but only property which we need is MaxLength is missing. Due to this you can enter as many character as you can in the textBox or you can say textArea control.In the Example i have the problem form which show you the real problem. You can see the html of the page by right clicking with mouse and then clicking the View Source of the page.

Solution:

There are many solutions you can use using Javascript or JQuery. but the easiest way to solve this problem without using any scripts is using another little hidden feature within .Net!

.Net kindly ignores the ‘MaxLength’ attribute for a textbox with it’s ‘TextMode’ set to ‘MultiLine’, if it is set within the frontend files.

Woop! Why; I’m not sure, but the simple workaround is to do this within the backend. Personally I choose to do it within the PreRender method.

VB.NET

' Add MaxLength attribute via code
TextBox2.Attributes.Add("maxlength", "5")

C#

// Add MaxLength attribute via code
TextBox2.Attribute.Add("maxlength", "5");

That’s all folks! Keeping it nice and simple ;)


tags