TextBoxNumOnly.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Drawing;
  3. using System.Windows.Forms;
  4. namespace UAS_MES_NEW.CustomControl.TextBoxWithIcon
  5. {
  6. public partial class TextBoxNumOnly : TextBox
  7. {
  8. public TextBoxNumOnly()
  9. {
  10. InitializeComponent();
  11. this.KeyPress += OnKeyPress;
  12. this.Enter += OnEnter;
  13. this.Leave += OnLeave;
  14. }
  15. /// <summary>
  16. /// 防止返回的内容为空
  17. /// </summary>
  18. public override string Text
  19. {
  20. get
  21. {
  22. //如果未输入值则自动的返回0,防止值类型转换的时候进行异常处理
  23. if (base.Text == "")
  24. {
  25. return "0";
  26. }
  27. return base.Text;
  28. }
  29. set
  30. {
  31. base.Text = value;
  32. }
  33. }
  34. private void OnKeyPress(object sender, KeyPressEventArgs e)
  35. {
  36. if (e.KeyChar != '\b')//这是允许输入退格键
  37. {
  38. if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字
  39. {
  40. e.Handled = true;
  41. }
  42. }
  43. }
  44. private void OnEnter(object sender, EventArgs e)
  45. {
  46. BackColor = Color.GreenYellow;
  47. }
  48. private void OnLeave(object sender, EventArgs e)
  49. {
  50. BackColor = Color.White;
  51. }
  52. }
  53. }