private void NoTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
char kc = e.KeyChar;
if ((kc < 48 || kc > 57) && kc != 8 && kc != 46)
{
e.Handled = true;
}
if (kc == 8)
{
e.Handled = false;
}
else
{
e.Handled = !IsNumeric(this.NoTextBox, e.KeyChar.ToString());
}
}
/// <summary>
/// 数値パターン
/// </summary>
private readonly Regex numericPattern = new Regex("^([0-9])*$");
/// <summary>
/// 数値(整数型)
/// </summary>
private readonly Regex integerPattern = new Regex(@"^\d+$");
/// <summary>
/// 数値(小数型)
/// </summary>
private readonly Regex floatPattern = new Regex(@"^[+-]?\d*[.]?\d*$");
/// <summary>
/// 数値(符号なし小数型)
/// </summary>
private readonly Regex unsignedFloatPattern = new Regex(@"^\d*[.]?\d*$");
/// <summary>
/// 数値の型
/// </summary>
public enum NumericMode
{
/// <summary>
/// 数値
/// </summary>
Numeric = 0,
/// <summary>
/// 整数型
/// </summary>
Integer = 1,
/// <summary>
/// 小数型
/// </summary>
Float = 2,
/// <summary>
/// 符号なし小数型
/// </summary>
UnsignedFloat = 3
}
private bool IsNumeric(TextBox txtBox, string value, NumericMode NumericType = NumericMode.Numeric, int DecimalPlaces = 0)
{
if (value.Length == 0)
{
return true;
}
bool result = true;
switch (NumericType)
{
case NumericMode.Numeric:
result = numericPattern.IsMatch(value);
break;
case NumericMode.Integer:
result = integerPattern.IsMatch(value);
if (result)
{
if ("0".Equals(txtBox.Text))
{
txtBox.Text = string.Empty;
}
}
break;
case NumericMode.Float:
result = floatPattern.IsMatch(value);
if (result && DecimalPlaces == 0 && ".".Equals(value))
{
result = false;
}
if (result && txtBox.Text.Contains("."))
{
string[] arrInputValue = txtBox.Text.Split('.');
if (arrInputValue.Length == 2
&& arrInputValue[1].Length >= DecimalPlaces)
{
result = false;
}
}
if (result)
{
if ("0".Equals(txtBox.Text) && !".".Equals(value))
{
txtBox.Text = string.Empty;
}
}
break;
case NumericMode.UnsignedFloat:
result = unsignedFloatPattern.IsMatch(value);
if (result && DecimalPlaces == 0 && ".".Equals(value))
{
result = false;
}
if (result && txtBox.Text.Contains("."))
{
string[] arrInputValue = txtBox.Text.Split('.');
if (arrInputValue.Length == 2
&& arrInputValue[1].Length >= DecimalPlaces)
{
result = false;
}
}
if (result)
{
if ("0".Equals(txtBox.Text) && !".".Equals(value))
{
txtBox.Text = string.Empty;
}
}
break;
}
return result;
}