ASP.NET TextBox MaxLength in Multiline-Mode

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.

Single line textboxes render as an HTML <input> tag - which supports a max
length.

The Multiline Textbox, renders as an HTML <TextArea> which doesn't support a
length property.

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.
posted on 2007-11-28 17:07  Willson  阅读(1007)  评论(0编辑  收藏  举报