C# 文本框按键事件处理,用于0到9999999999.99之间的小数

C# 文本框按键事件处理,用于0到9999999999.99之间的小数,c#,winforms,C#,Winforms,我需要一个文本框按键处理程序,它处理0到9999999999.99的十进制输入范围值。我有下面的代码,但不起作用。有了它,我就不能输入10位数后的小数了 public static void NumericWithDecimalTextBox_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&

我需要一个文本框按键处理程序,它处理0到9999999999.99的十进制输入范围值。我有下面的代码,但不起作用。有了它,我就不能输入10位数后的小数了

public static void NumericWithDecimalTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
        (e.KeyChar != '.'))
    {
        e.Handled = true;
    }

    TextBox textBox = sender as TextBox;
    string[] parts = textBox.Text.Split('.');

    // only allow one decimal point
    if (((e.KeyChar == '.') && (textBox.Text.IndexOf('.') > -1)) || (!char.IsControl(e.KeyChar) && ((parts[0].Length >= 10))))
    {
        e.Handled = true;
    }
}

您可以通过验证数据来简化流程,方法如下:

public static void NumericWithDecimalTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    var textBox = sender as TextBox;
    var enteredValue = textBox.Text;
    var decimalValue = 0M;

    if (decimal.TryParse(enteredValue, out decimalValue) && ValueIsWithinRange(decimalValue, 0M, 9999999999.99M))
    {
        Model.ThePropertyStoringTheValue = decimalValue; // wherever you need to store the value
    }
    else
    {
        // Inform the user they have entered invalid data (i.e. change the textbox background colour or show a message box)
    }
}

private bool ValueIsWithinRange(decimal valueToValidate, decimal lower, decimal upper)
{
    return valueToValidate >= lower && valueToValidate <= upper
}
public static void NumericWithDecimalTextBox\u按键(对象发送器,按键事件参数e)
{
var textBox=发送方作为textBox;
var enteredValue=textBox.Text;
var小数值=0M;
if(小数点TryParse(输入值,输出小数点值)和&valueiswithin范围(小数点值,0M,9999999999.99M))
{
Model.ThePropertyStoringTheValue=decimalValue;//需要存储值的任何位置
}
其他的
{
//通知用户他们输入了无效数据(即更改文本框背景颜色或显示消息框)
}
}
私有布尔值在范围内(十进制值验证、十进制下限、十进制上限)
{

对不起,我已经纠正了这个问题。@ MJWILE只允许10位数字前缀为十进制。考虑将<代码> 10 < /代码>改为<代码> 13 /代码>。然后尝试使用<代码>双。TyPARSE <代码> >代码> Text Box。