Asp.net中TextBox的MaxLength无效问题(转载)

今天早上一来,有位测试的同事告诉我,你昨天提交的代码其中有个限制TextBox字符数的作用根本没有效果啊。 我还坚定的告诉他,怎么可能呢?我肯定做了MaxLength的限制。于是我赶忙打开电脑自己测试一下,果然字符限制没有作用。 经过对比琢磨终于明白了是微软出了问题。 TextBox控件在TextMode=“MultiLine”时,MaxLength属性的限制就失去了作用。为什么会这样,我到现在也没弄明白,也许是微软的一个Bug吧。不过这个限制可以有如下方法解决:
方法一: 验证控件(经实践可行)

<asp:TextBox ID="txtConclusion" MaxLength="200" TextMode="MultiLine" Height="100px" Width="400px" runat="server"/>
<asp:RegularExpressionValidator ID="txtConclusionValidator1" ControlToValidate="txtConclusion" 
Text="超过200字" ValidationExpression="^[\s\S]{0,200}$" runat="server"/>

方法二:添加一些客户端限制的JS代码。示例如下: 
 
<HTML>
    <HEAD>
        <title>WebForm6</title>
        <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        <meta name="CODE_LANGUAGE" Content="C#">
        <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
        <script language="javascript">            
            function isOver(sText,len)
            {
                var intlen=sText.value.length;
                if (intlen>len)
                {
                    alert("The content length must Less than or Equal "+len);
                    sText.focus();
                    sText.select();
                }
            }
        </script>
    </HEAD>
    <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <asp:TextBox id="txtName" style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 104px" runat="server"
                TextMode="MultiLine" Height="112px" Width="271px"></asp:TextBox>
        </form>
    </body>
</HTML>
  
Public void Page_Load(object sender, System.EventArgs e)
{
     this.txtName.Attributes.Add("onblur","isOver(this,1000);");
}
 

方法三:写一个自定义控件,参见http://www.codeproject.com/KB/aspnet/Textarea_Length_Validator.aspx
 
转载自:http://www.cnblogs.com/supercom/archive/2009/10/16/1584331.html

posted on 2012-08-23 17:09  zhuhai  阅读(605)  评论(0)    收藏  举报

导航

我的百度空间