C# TextBox中只允许输入数字的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar.Controls;

namespace WinDrilling.ErrorJudge.Class
{
class ClsTxtOperate
{
#region TextBoxX控件只能输入数字函数
//只能输入数字函数
public static void InputNumOnly(TextBoxX MyChecnkTxt, KeyPressEventArgs e)
{
//判断按键是不是要输入的类型。
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
e.Handled = true;

//小数点的处理。
if ((int)e.KeyChar == 46) //小数点
{
if (MyChecnkTxt.Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(MyChecnkTxt.Text, out oldf);
b2 = float.TryParse(MyChecnkTxt.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}
#endregion
}
}

原文地址:https://www.cnblogs.com/yuxuetaoxp/p/3873771.html