范围为 0 到 999999999.99 的小数的 TextBox 按键事件处理



我需要一个文本框按键处理程序来处理 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
}

这样,如果值有效,则会将其写入模型(遵循良好的 MVC 设计实践(,如果无效,则会向用户发送一条消息,允许他们进行更正(例如,"您输入的值不是有效的小数"或"该值不得为负数"等(。

最新更新