ASP.NET TextBox MaxLength in Multiline-Mode
Section: ASP.NETRating: Not rated yet!

Add to YiGGAdd to google-bookmarksAdd to linkarenaAdd to redditAdd to del.icio.usAdd to misterwongAdd to digg




Introduction

The ASP.NET-TextBox in Multiline-Mode has a little problem: The MaxLength-property has no effect. This article shows how to workaround this problem with a nice javascript-hack.

Register javascript in Page_Load


The only thing you need to do is to register a ClientScriptBlock in the Page_Load-eventhandler of the ASPX where you use your multiline TextBox:

const int LENGTH_TEXT = 100; protected void Page_Load(object sender, EventArgs e) { string lengthFunction = "function isMaxLength(txtBox) {"; lengthFunction += " if(txtBox) { "; lengthFunction += " return ( txtBox.value.length <=" + LENGTH_TEXT + ");"; lengthFunction += " }"; lengthFunction += "}"; this.txtMyTextBox.Attributes.Add("onkeypress", "return isMaxLength(this);"); ClientScript.RegisterClientScriptBlock( this.GetType(), "txtLength", lengthFunction , true); }

If the length of the TextBox named txtMyTextBox exceeds the value of LENGTH_TEXT, the function isMaxLength returns false and there is no keypress possible anymore. Oh, I loves workarounds:-)




 Reader-Comments:

Noorul Ameen
5/22/2007 7:45:24 AM

Good Work

Nice to control the text length in TextArea.