自定义控件(输入框,数字)

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls.Adapters;

namespace LBControl
{
    public class LBTextBox:System.Web.UI.WebControls.TextBox
    {
        private TBType tbtype;
        public TBType TBTYPE
        {
            get {return tbtype;}
            set { tbtype = value; }
        }

        public enum TBType
        {
            onlyint = 1,
            onlyfloat=2,
            onlyint2=3
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (tbtype == TBType.onlyint)
            {
                this.Attributes.Add("onkeypress", @"var k=event.keyCode; if((k<=57 && k>=48)){ if(k==46) { if(this.value.indexOf('.')>=0) { return false; } else { if(this.value==''){return false;}return true;} }}else return false;");
                this.Attributes.Add("onpaste", "return false");
                this.Style.Add("ime-mode", "disabled");
                this.ToolTip = "只能输入数字";
            }
            else if (tbtype == TBType.onlyfloat)
            {
                this.Attributes.Add("onkeypress", @"var k=event.keyCode; if((k==46)||(k<=57 && k>=48)){ if(k==46) { if(this.value.indexOf('.')>=0) { return false; } else { if(this.value==''){return false;}return true;} }}else return false;");
                this.Attributes.Add("onpaste", "return false");
                this.Style.Add("ime-mode", "disabled");
                this.ToolTip = "只能输入整数和小数";
            }
            else if (tbtype == TBType.onlyint2)
            {
                this.Attributes.Add("onKeyUp", "this.value=DBC2SBC(this.value);");
                this.ToolTip = "只能输入整数";
                string dopost = "";
                dopost += "<script type=text/javascript>\n";
                dopost += "      function DBC2SBC(str){\n";
                dopost += "          var i;var result='';for(i=0;i<str.length;i++) {if(str.charCodeAt(i)>65295 && str.charCodeAt(i)<65306) result+=String.fromCharCode(str.charCodeAt(i)-65248); else if(str.charCodeAt(i)>47 && str.charCodeAt(i)<58) result+=String.fromCharCode(str.charCodeAt(i)); } return result; } \n";
                dopost += "</script>\n";
                if (!Page.ClientScript.IsClientScriptIncludeRegistered(this.GetType(), "DBC2SBC"))
                {
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DBC2SBC", dopost);
                }
            }
            else
            { }
        }
    }
}

前台使用,选择TBTYPE类型

如:<cc1:LBTextBox ID="LBTextBox2" runat="server" TBTYPE="onlyint2">

原文地址:https://www.cnblogs.com/lsfv/p/1446391.html