在 C# 中,在数字文本框中,如何防止小数点仅作为第一位数字放置?
In C#, in a numerical textbox, how do I prevent a decimal point being placed in as the first digit only?
目前我有这个防止字符输入的代码,并且多了一位小数,
但是如何防止第一个字符是小数呢?
private void textBoxNoLetters_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
{
e.Handled = true;
}
else if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
以下是您的代码,已修改以处理小数点分隔符,此外还获取系统的小数点分隔符以帮助本地化您的应用程序。
char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back && e.KeyChar != decimalChar)
{
e.Handled = true;
}
else if ((e.KeyChar == decimalChar) && ((sender as TextBox).Text.IndexOf(decimalChar) > -1))
{
e.Handled = true;
}
else if ((e.KeyChar == decimalChar) && ((sender as TextBox).Text.Length == 0))
{
e.Handled = true;
}
目前我有这个防止字符输入的代码,并且多了一位小数,
但是如何防止第一个字符是小数呢?
private void textBoxNoLetters_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
{
e.Handled = true;
}
else if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
以下是您的代码,已修改以处理小数点分隔符,此外还获取系统的小数点分隔符以帮助本地化您的应用程序。
char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back && e.KeyChar != decimalChar)
{
e.Handled = true;
}
else if ((e.KeyChar == decimalChar) && ((sender as TextBox).Text.IndexOf(decimalChar) > -1))
{
e.Handled = true;
}
else if ((e.KeyChar == decimalChar) && ((sender as TextBox).Text.Length == 0))
{
e.Handled = true;
}