只能输入数字的winForm的TextBox文字框

using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsApplication3
{

 //[ToolboxBitmap(typeof(NumericTextBox), "NumericTextBox.ico")]
 public class NumericTextBox : System.Windows.Forms.TextBox
 {
  public delegate void InvalidUserEntryEvent(object sender,KeyPressEventArgs e);
  public event InvalidUserEntryEvent InvalidUserEntry;


  /// <summary>
  /// Required designer variable.
  /// </summary>
  private System.ComponentModel.Container components = null;

  public NumericTextBox(System.ComponentModel.IContainer container)
  {
   /// <summary>
   /// Required for Windows.Forms Class Composition Designer support
   /// </summary>
   container.Add(this);
   InitializeComponent();

   //
   // TODO: Add any constructor code after InitializeComponent call
   //
  }

  public NumericTextBox()
  {
   /// <summary>
   /// Required for Windows.Forms Class Composition Designer support
   /// </summary>
   InitializeComponent();

   //
   // TODO: Add any constructor code after InitializeComponent call
   //
  }

  #region Component Designer generated code
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {
   components = new System.ComponentModel.Container();
  }
  #endregion

  protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
  {
   int asciiInteger = Convert.ToInt32(e.KeyChar);
   if (asciiInteger >= 47 && asciiInteger <= 57)
   {
    //If the value of the ASCII converted char type (e.KeyChar) represents 0-9
    //pass the event to Windows for default processing
    e.Handled = false;
    return;
   }
   //If the value of the ASCII converted char type (e.KeyChar) represents BACKSPACE
   //pass the event to Windows for default processing
   if (asciiInteger == 8)
   {
    e.Handled = false;
    return;
   }
   //If the value of the ASCII converted char type (e.KeyChar) is anything else
   //handle the event here by setting Handled=true which prevents the event from being
   //passed Windows for default processing
   e.Handled = true;
   if (InvalidUserEntry != null)
    InvalidUserEntry(this, e);
  }
  public override string Text
  {
   get
   {
    return base.Text;
   }
   set
   {
    try
    {
     int.Parse(value);
     base.Text = value;
     return;
    }
    catch
    {}
    if (value == null)
    {
     base.Text = value;
     return;
    }
   } 
  }
 }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值