让TextArea支持MaxLength的自定义文本框控件

众所周知,TextArea并不支持MaxLength属性,所以我们就用JS来实现MaxLength的功能。
代码如下:
 1    public   class  TextMultiLine : TextBox
 2      {
 3        private const string SCP_SELECTPRODUCT_ONLY_SCRIPT_ID = "{A19D31C2-A21B-4acd-92DA-19A4237C54A8}";
 4        /// <summary>
 5        /// 
 6        /// </summary>

 7        public override TextBoxMode TextMode
 8        {
 9            get
10            {
11                return TextBoxMode.MultiLine;
12            }

13        }

14
15        /// <summary>
16        /// 
17        /// </summary>
18        /// <param name="writer"></param>

19        protected override void AddAttributesToRender(HtmlTextWriter writer)
20        {
21            base.AddAttributesToRender(writer);
22            writer.AddAttribute("onpaste""return false;");
23            writer.AddAttribute("onpcopy""return false;");
24            if (base.MaxLength > 0)
25            {
26                writer.AddAttribute("onkeydown""textCounter(this,"+base.MaxLength+");");
27                writer.AddAttribute("onkeyup""textCounter(this,"+base.MaxLength+");");
28            }

29        }

30
31        /// <summary>
32        /// 
33        /// </summary>
34        /// <param name="e"></param>

35        protected override void OnPreRender(EventArgs e)
36        {
37            base.OnPreRender(e);
38            RenderJavaScript();
39        }

40        /// <summary>
41        /// 
42        /// </summary>

43        private void RenderJavaScript()
44        {
45            string SCP_SELECTPRODUCT_ONLY_SCRIPT =
46                    "function textCounter(field, maxlimit)\n" +
47                    "{\n" +
48                        "if (field.value.length > maxlimit) \n" +
49                        "{\n" +
50                //如果元素区字符数大于最大字符数,按照最大字符数截断; 
51                            "field.value = field.value.substring(0, maxlimit); \n" +
52                        "}\n" +
53                    "}";                    
54
55            if (!Page.ClientScript.IsClientScriptBlockRegistered(SCP_SELECTPRODUCT_ONLY_SCRIPT_ID))
56            {
57                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), SCP_SELECTPRODUCT_ONLY_SCRIPT_ID, SCP_SELECTPRODUCT_ONLY_SCRIPT,true);
58            }

59        }

60    }

你可能感兴趣的:(textarea)