Click here to Skip to main content
12,825,583 members (37,154 online)
Click here to Skip to main content
Add your own
alternative version


79 bookmarked
Posted 30 Aug 2007

Extending the ASP.NET multiline TextBox control to limit the number of characters entered

, 16 Nov 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
Developers use multiline TextBox controls in almost all web projects. Since the MaxLength property of a TextBox control does not work when the TextMode property is set to Multiline, we usually use Validator controls to validate the length.


Developers use multiline TextBox controls in almost all web projects. Since the MaxLength property of a TextBox control does not work when the TextMode property is set to Multiline, we usually use Validator controls to validate the length. In this hands-on article, we are going to extend the TextBox control using JavaScript in order to limit the number of characters entered by the user to the length specified.

Using the code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Globalization;
using System.Threading;

namespace CustomServerControls
    [ToolboxData("<{0}:TextArea runat="server"></{0}:TextArea>")]
    public class TextArea : TextBox
        public override TextBoxMode TextMode
                return TextBoxMode.MultiLine;

        protected override void OnPreRender(EventArgs e)
            if (MaxLength > 0)
                if (!Page.ClientScript.IsClientScriptIncludeRegistered("TextArea"))
                this.Attributes.Add("onkeyup", "LimitInput(this)");
                this.Attributes.Add("onbeforepaste", "doBeforePaste(this)");
                this.Attributes.Add("onpaste", "doPaste(this)");
                this.Attributes.Add("onmousemove", "LimitInput(this)");
                this.Attributes.Add("maxLength", this.MaxLength.ToString());

The code above creates a new TextArea custom server control by extending ASP.NET's TextBox control. By overriding the OnPreRender function, we include attributes to the HTML of the control. We add custom JavaScript and a property to pass MaxLength on the client side.

To show the working TextArea control, I prepared the following HTML:

<%@ Page Language="C#" AutoEventWireup="true" 
         CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register TagPrefix="csc" Namespace="CustomServerControls" %>

In the above HTML, I register the custom control with the web page by using the following line:

<%@ Register TagPrefix="csc" Namespace="CustomServerControls" %>

If you don't want to add the above registration line on each page that you use the TextArea control, you may add the following statement in the system.web section of the web.config file:

    <add tagPrefix="csc" namespace="CustomServerControls"></add>

I added the control on the page as:

<csc:TextArea id="TextArea" runat="server" MaxLength="105" Rows="10" Width="300px">

Let's compare the rendered output of a multiline textbox control and our text area control:

The rendered output of a standard multiple line ASP.NET TextBox is:

<textarea name="TextArea" id="TextArea" rows="10" cols="20" style="width:300px;" ></textarea>

The rendered output of our TextArea custom server control is:

<textarea name="TextArea" rows="10" cols="20" id="TextArea"
  onkeypress="LimitInput(this)" onbeforepaste="doBeforePaste(this)"
  onpaste="doPaste(this)" onmousemove="LimitInput(this)" maxLength="105"

The JavaScript event handlers doBeforePaste and doPaste are only implemented in Internet Explorer. These event handlers are used to check the length of characters that are pasted by using a mouse in Internet Explorer. Unfortunately, the doBeforePaste and doPaste event handlers are not defined in other browsers and we cannot catch a mouse paste in browsers other than IE. Therefore, I added an onmousemove event handler in order to check the length of characters that are pasted by using a mouse after a mouse move. The onkeypress event handler handles the standard character input.

function doBeforePaste(control)
   maxLength = control.attributes["maxLength"].value;
       event.returnValue = false;
function doPaste(control)
   maxLength = control.attributes["maxLength"].value;
   value = control.value;
        event.returnValue = false;
        maxLength = parseInt(maxLength);
        var o = control.document.selection.createRange();
        var iInsertLength = maxLength - value.length + o.text.length;
        var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
        o.text = sData;
function LimitInput(control)
    if(control.value.length >


  • Nov 10, 2007 - The onkeypress JavaScript event handler is changed with the onkeyup JavaScript event handler. (You may check the reason at KeyPress, KeyDown, KeyUp - The Difference Between JavaScript Key Events)
  • Nov 9, 2007 - Instead of using the 'ResolveClientUrl' method to access textarea.js which may cause a problem in the case of URL rewriting, the 'ResolveUrl' method is used.
  • The code is tested on Firefox, IE 6.0, and IE 7.0.

      Try the online demo of the extended ASP.NET multiline TextBox control that limits the number of characters entered. You may find more articles about ASP.NET, JavaScript, and C# on my blog.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

blogging developer
Web Developer
Blogging Developer is an accomplished project manager with more than 8 years of experience in web development, web strategy, e-commerce, and search engine optimization, specialized in object-oriented, multi-tiered design and analysis with hands-on experience in the complete life cycle of the implementation process including requirements analysis, prototyping, proof of concept, database design, interface implementation, testing, and maintenance.

Solid project management skills, expertise in leading and mentoring individuals to maximize levels of productivity, while forming cohesive team environments.

You may also be interested in...


Comments and Discussions

GeneralHi Pin
srinath g nath24-Nov-07 9:01
membersrinath g nath24-Nov-07 9:01 
QuestionWhy not just use a Regular Expression? Pin
orengold21-Nov-07 8:13
memberorengold21-Nov-07 8:13 
AnswerRe: Why not just use a Regular Expression? Pin
blogging developer21-Nov-07 11:03
memberblogging developer21-Nov-07 11:03 
GeneralRe: Why not just use a Regular Expression? Pin
orengold21-Nov-07 11:52
memberorengold21-Nov-07 11:52 
GeneralFirefox counts characters different from IE (AFAIK) [modified] Pin
Mark Cranness19-Nov-07 15:37
memberMark Cranness19-Nov-07 15:37 
Generalonkeypress Pin
Paulius9-Nov-07 3:10
memberPaulius9-Nov-07 3:10 
GeneralRe: onkeypress Pin
blogging developer9-Nov-07 23:53
memberblogging developer9-Nov-07 23:53 
QuestionResolveClientUrl problem? Pin
tvj088-Nov-07 7:14
membertvj088-Nov-07 7:14 
AnswerRe: ResolveClientUrl problem? Pin
blogging developer8-Nov-07 7:23
memberblogging developer8-Nov-07 7:23 
GeneralGood Pin
rajantawate1(http// 12:10
memberrajantawate1(http// 12:10 
Generaldesigner.vb Pin
aurand20-Sep-07 12:35
memberaurand20-Sep-07 12:35 
GeneralRe: designer.vb Pin
blogging developer20-Sep-07 22:42
memberblogging developer20-Sep-07 22:42 
GeneralRe: designer.vb Pin
aurand21-Sep-07 3:19
memberaurand21-Sep-07 3:19 
GeneralRe: designer.vb Pin
blogging developer21-Sep-07 3:26
memberblogging developer21-Sep-07 3:26 
GeneralRe: designer.vb Pin
aurand21-Sep-07 3:27
memberaurand21-Sep-07 3:27 
QuestionIs there any posible answer? Pin
Mahdi Yousefi18-Sep-07 21:17
memberMahdi Yousefi18-Sep-07 21:17 
AnswerRe: Is there any posible answer? Pin
blogging developer18-Sep-07 21:24
memberblogging developer18-Sep-07 21:24 
GeneralNice article and responses to questions! Pin
Kevin Jensen9-Sep-07 5:15
memberKevin Jensen9-Sep-07 5:15 
GeneralRe: Nice article and responses to questions! Pin
blogging developer9-Sep-07 7:34
memberblogging developer9-Sep-07 7:34 
GeneralFor regular TEXTAREA HTML tag Pin
aadavis4-Sep-07 8:28
memberaadavis4-Sep-07 8:28 
GeneralRe: For regular TEXTAREA HTML tag Pin
blogging developer4-Sep-07 11:58
memberblogging developer4-Sep-07 11:58 
GeneralRe: For regular TEXTAREA HTML tag Pin
aadavis4-Sep-07 14:00
memberaadavis4-Sep-07 14:00 
Generalonbeforepaste, onpaste events are not necessary Pin
Justin Keyes3-Sep-07 18:15
memberJustin Keyes3-Sep-07 18:15 
GeneralRe: onbeforepaste, onpaste events are not necessary Pin
blogging developer3-Sep-07 21:27
memberblogging developer3-Sep-07 21:27 
GeneralGood Idea Pin
merlin98131-Aug-07 5:35
membermerlin98131-Aug-07 5:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170308.1 | Last Updated 16 Nov 2007
Article Copyright 2007 by blogging developer
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid