How to set MaxLength property of multiline textbox

Introduction: In this article I am going to share the trick to set the maximum number of characters that can be entered in multiline textbox using both C# and VB languages.

How to set MaxLength property of multiline textbox

Description: We all know that we can set the maximum allowed characters in normal textbox by setting its MaxLength property to desired number of characters. But same doesn’t work if the TextMode property of textbox is set to Multiline.

When a Textbox is in SingleLine mode which is default TextMode , it gets rendered as an input type textbox  and when we set its TextMode property  to MultiLine, it gets rendered as a textarea. As we know, MaxLength property works only for input type and not for textarea. But There are multiple ways to handle this using javascript,  jquery or regular expression. But I got the simple solution to handle this without using jquery or regularexpression.
Implementation:  Let’s create an example to demonstrate this.

HTML Source
<html xmlns="">
<head runat="server">
    <title> Set Max Length of multiline textbox </title>
    <form id="form1" runat="server">
       <fieldset style="width:300px;">
           <legend>Set max length of multiline textbox</legend>
           <asp:TextBox ID="txtComments" runat="server" Width="300px" TextMode="MultiLine" MaxLength="60" placeholder="Max allowed:60 characters"></asp:TextBox>

Asp.Net C# code to set max length of multiline textbox

protected void Page_Load(object sender, EventArgs e)
        if (!Page.IsPostBack)
            txtComments.Attributes.Add("maxlength", txtComments.MaxLength.ToString());
Asp.Net VB code to set max length of multiline textbox

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If (Not Page.IsPostBack) Then
            txtComments.Attributes.Add("maxlength", txtComments.MaxLength.ToString())
        End If
    End Sub

Now over to you:
"A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..