Monday, June 16, 2008

ASP.net: Set MaxLength in muliti-line textbox

When set the MaxLength property in the textbox, it will prevent user to enter text longer than the MaxLength value. However, when you change the TextMode from SingleLine to MultiLine, the MaxLength property has no effect.

Here is a work-around for this issue:
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);

}
Click here for more detail.

No comments: