日期:2014-05-18 浏览次数:21702 次
控制只能输入整数或小数(供TextBox注册KeyPress事件)#region 控制只能输入整数或小数(供TextBox注册KeyPress事件) /**//// <summary> /// 控制只能输入整数或小数 /// (小数位最多位4位,小数位可以自己修改) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Txb_Decimal_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if(!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31)) { if(e.KeyChar == '.') { if ( ((TextBox)sender).Text.Trim().IndexOf('.') > -1) e.Handled = true; } else e.Handled = true; } else { if( e.KeyChar <= 31 ) { e.Handled = false ; } else if( ((TextBox)sender).Text.Trim().IndexOf('.') > -1 ) { if( ((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1 ).Length >= 4) e.Handled = true ; } } } #endregion
------解决方案--------------------
http://www.soft000.com/lt/topic.asp?l_id=6&t_id=68
重写TEXTBOX
------解决方案--------------------
这是我重写的一个TextBox控件,希望对你有用
/**********************************************************************
* Created by : Sunny.li
* Create Date: 2007/11/09
* Description:
* Samples :
*
**********************************************************************/
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace MyApp
{
public class NumberBox : System.Windows.Forms.TextBox
{
public NumberBox()
{
this.TextAlign = HorizontalAlignment.Right;
}
public enum NumberType
{
intNumber,
DecimalNumber
}
private NumberType numberType = NumberType.intNumber;
/// <summary>
/// get or set the Number Type
/// </summary>
public NumberType Numbertype
{
get
{
return numberType;
}
set
{
numberType = value;
}
}
private int iNumberLength = 10;
/// <summary>
/// get or set the integral' length of Number
/// </summary>
public int INumberLength
{
set
{
iNumberLength = value;
}
get
{
return iNumberLength;
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (numberType == NumberType.intNumber)
{
if (IsNum(e.KeyChar))
e.Handled = false;//允许输出
else
e.Handled = true;//禁止输出
}
else
{
if (IsDecimal(e.KeyChar))
e.Handled = false;//允许输出