using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace UAS_MES_NEW.CustomControl.TextBoxWithIcon { public partial class TextBoxNumOnly : TextBox { public TextBoxNumOnly() { InitializeComponent(); this.KeyPress += OnKeyPress; this.Enter += OnEnter; this.Leave += OnLeave; } /// /// 防止返回的内容为空 /// public override string Text { get { //如果未输入值则自动的返回0,防止值类型转换的时候进行异常处理 if (base.Text == "") { return "0"; } return base.Text; } set { base.Text = value; } } private void OnKeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar != '\b')//这是允许输入退格键 { if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字 { e.Handled = true; } } } private void OnEnter(object sender, EventArgs e) { BackColor = Color.GreenYellow; } private void OnLeave(object sender, EventArgs e) { BackColor = Color.White; } } }