Click here to Skip to main content
6,295,667 members and growing! (12,183 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Beginner

Extending the ASP.Net Multiline TextBox control to limit the number of characters entered

By blogging developer

Developers use multiline TextBox controls in almost all web projects. Since 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.
Javascript, HTML, C# 2.0, Windows, .NET 2.0, ASP.NET, WebForms, IIS 5.1, IIS 6, VS2005, IE 6.0, IE 5.5, IE 7, Dev
Posted:30 Aug 2007
Updated:16 Nov 2007
Views:70,344
Bookmarked:64 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
37 votes for this article.
Popularity: 6.87 Rating: 4.38 out of 5

1
1 vote, 2.7%
2
2 votes, 5.4%
3
8 votes, 21.6%
4
26 votes, 70.3%
5

Introduction

Developers use multiline TextBox controls in almost all web projects. Since 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
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:TextArea runat="server"></{0}:TextArea>")]
    public class TextArea : TextBox
    {
        public override TextBoxMode TextMode
        {
            get
            {
                return TextBoxMode.MultiLine;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (MaxLength > 0)
            {
                if (!Page.ClientScript.IsClientScriptIncludeRegistered("TextArea"))
                {
                    Page.ClientScript.RegisterClientScriptInclude("TextArea", ResolveUrl("~/textarea.js"));
                }
                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());
            }
                base.OnPreRender(e);
        }
    }
}
 

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 javascripts and a property to pass maxLength on 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" %> 

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>TextArea Custom Server Control with MaxLength property</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <csc:TextArea id="TextArea" runat="server" MaxLength="105" Rows="10" Width="300px"></csc:TextArea>
    </div>
    </form>
</body>
</html>

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 system.web section of the web.config file.

<pages>
   <controls>
    <add tagPrefix="csc" namespace="CustomServerControls"></add>
   </controls>
</pages>  
I added the control on page as:
<csc:TextArea id="TextArea" runat="server" MaxLength="105" Rows="10" Width="300px"></csc:TextArea>
Let's compare the rendered output of a multiline textbox control and our text area control:

Rendered output of a standard multiple line Asp.Net TextBox is:
<textarea name="TextArea" id="TextArea" rows="10" cols="20" style="width:300px;" ></textarea> 

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"
style="width:300px;"></textarea>

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, 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;
   if(maxLength)
   {
       event.returnValue = false;
   }
}
function doPaste(control)
{
   maxLength = control.attributes["maxLength"].value;
   value = control.value;
   if(maxLength){
        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 >

Updates:

Nov 10th, 2007 - onkeypress javascript event handler is changed with onkeyup javascript event handler. (You may check the reason at KeyPress, KeyDown, KeyUp - The Difference Between Javascript Key Events)

Nov 9th, 2007 - instead of using 'ResolveClientUrl' method to access textarea.js which may cause a problem in case of url rewriting, 'ResolveUrl' method is used.

The code is tested on Firefox, IE 6.0 and IE 7.0.

Try the online demo of extended Asp.net multiline TextBox control that limits the number of characters entered.

You may find more articles about Asp.net, JavaScript, C# on my blog.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

blogging developer


Member
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.
Occupation: Web Developer
Location: United States United States

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 32 (Total in Forum: 32) (Refresh)FirstPrevNext
GeneralSet MaxLength from CodeBehind PinmemberKen Robert Andersen0:34 8 May '09  
GeneralThanks PinmemberGrettir Strong8:34 6 Feb '09  
GeneralNice Solution PinmemberAlpha_Jujster4:02 2 Feb '09  
Generalvalidation not working quite right PinmemberHalfHuman2:13 7 Jan '08  
GeneralHi Pinmembersrinath g nath9:01 24 Nov '07  
GeneralWhy not just use a Regular Expression? Pinmemberorengold8:13 21 Nov '07  
GeneralRe: Why not just use a Regular Expression? Pinmemberblogging developer11:03 21 Nov '07  
GeneralRe: Why not just use a Regular Expression? Pinmemberorengold11:52 21 Nov '07  
GeneralFirefox counts characters different from IE (AFAIK) [modified] PinmemberMark Cranness15:37 19 Nov '07  
Generalonkeypress PinmemberPaulius3:10 9 Nov '07  
GeneralRe: onkeypress Pinmemberblogging developer23:53 9 Nov '07  
GeneralResolveClientUrl problem? Pinmembertvj087:14 8 Nov '07  
GeneralRe: ResolveClientUrl problem? Pinmemberblogging developer7:23 8 Nov '07  
GeneralGood Pinmemberrajantawate1(http//www.jhatak.com)12:10 31 Oct '07  
Generaldesigner.vb Pinmemberaurand12:35 20 Sep '07  
GeneralRe: designer.vb Pinmemberblogging developer22:42 20 Sep '07  
GeneralRe: designer.vb Pinmemberaurand3:19 21 Sep '07  
GeneralRe: designer.vb Pinmemberblogging developer3:26 21 Sep '07  
GeneralRe: designer.vb Pinmemberaurand3:27 21 Sep '07  
QuestionIs there any posible answer? PinmemberMahdi Yousefi21:17 18 Sep '07  
AnswerRe: Is there any posible answer? Pinmemberblogging developer21:24 18 Sep '07  
GeneralNice article and responses to questions! PinmemberKevin Jensen5:15 9 Sep '07  
GeneralRe: Nice article and responses to questions! Pinmemberblogging developer7:34 9 Sep '07  
GeneralFor regular TEXTAREA HTML tag Pinmemberaadavis8:28 4 Sep '07  
GeneralRe: For regular TEXTAREA HTML tag Pinmemberblogging developer11:58 4 Sep '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 16 Nov 2007
Editor:
Copyright 2007 by blogging developer
Everything else Copyright © CodeProject, 1999-2009
Web17 | Advertise on the Code Project