TextBoxNumOnly.cs 1.6 KB

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