TextBox - 只允许数字和一个句号(代表十进制数) VB.NET

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15410903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:47:33  来源:igfitidea点击:

TextBox - Only allow Numeric and ONE full stop (representing a decimal number) VB.NET

.netvb.netwinformsvisual-studio-2010

提问by user1662306

I have the following code, and am looking to add in the fact it can allow only one decimal point (full stop) to be added anywhere within the string.

我有以下代码,我希望添加一个事实,它只能允许在字符串中的任何位置添加一个小数点(句号)。

If Asc(e.KeyChar) <> 8 Then
    If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
        e.Handled = True
    End If
End If

It will work by only accepting numeric numbers, so how can I incorporate ONE decimal point in this piece of code?

它将仅通过接受数字来工作,那么如何在这段代码中加入一个小数点?

Thanks

谢谢

回答by Steven Doggart

The Ascfunction is an old VB6 function which should be avoided when writing new .NET code. In this case, you could compare the character to see if it is in a certain range, like this:

Asc函数是旧的 VB6 函数,在编写新的 .NET 代码时应避免使用该函数。在这种情况下,您可以比较字符以查看它是否在某个范围内,如下所示:

If e.KeyChar <> ControlChars.Back Then
    If (e.KeyChar < "0"c) Or (e.KeyChar > "9"c) Then
        e.Handled = True
    End If
End If

However, I would suggest simply listing the valid characters, like this:

但是,我建议简单地列出有效字符,如下所示:

e.Handled = ("0123456789.".IndexOf(e.KeyChar) = -1)

As far as checking for multiple decimal points, you could do something in the key press event, like this:

至于检查多个小数点,您可以在按键事件中执行某些操作,如下所示:

If e.KeyChar = "."c Then
    e.Handled = (CType(sender, TextBox).Text.IndexOf("."c) <> -1)
ElseIf e.KeyChar <> ControlChars.Back Then
    e.Handled = ("0123456789".IndexOf(e.KeyChar) = -1)
End If

However, while it's nice to have the ability to filter out invalid key strokes, there are many problems with doing so. For instance, even with all of that checking, the following entries would all still be allowed, even though they, likely, should all be invalid:

然而,虽然能够过滤掉无效的击键很不错,但这样做也存在很多问题。例如,即使进行了所有这些检查,以下条目仍将被允许,即使它们很可能都应该是无效的:

  • 12.
  • 0000
  • 0001.
  • 12.
  • 0000
  • 0001。

The other big problem is that your code will be culture dependent. For instance, in Europe, often a comma is used as the decimal point. For these reasons, I would recommend, if possible, simply using Decimal.TryParsein the Validatingevent, like this:

另一个大问题是您的代码将依赖于文化。例如,在欧洲,经常使用逗号作为小数点。出于这些原因,如果可能的话,我建议Decimal.TryParseValidating事件中简单地使用,如下所示:

Private Sub TextBox1_Validating(sender As Object, e As CancelEventArgs) Handles TextBox1.Validating
    Dim control As TextBox = CType(sender, TextBox)
    Dim result As Decimal = 0
    Decimal.TryParse(control.Text, result)
    control.Text = result.ToString()
End Sub

回答by Sascha Hennig

Parse the string (text of the TextBox or whatever) to see whether it already contains a decimal point. Dont handle the keypress if thats the case:

解析字符串(TextBox 的文本或其他内容)以查看它是否已经包含小数点。如果是这种情况,请不要处理按键:

VB.NET:

VB.NET:

Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim FullStop As Char
    FullStop = "."

    ' if the '.' key was pressed see if there already is a '.' in the string
    ' if so, dont handle the keypress
    If e.KeyChar = FullStop And TextBox1.Text.IndexOf(FullStop) <> -1 Then
        e.Handled = True
        Return
    End If

    ' If the key aint a digit
    If Not Char.IsDigit(e.KeyChar) Then
        ' verify whether special keys were pressed
        ' (i.e. all allowed non digit keys - in this example
        ' only space and the '.' are validated)
        If (e.KeyChar <> FullStop) And
           (e.KeyChar <> Convert.ToChar(Keys.Back)) Then
            ' if its a non-allowed key, dont handle the keypress
            e.Handled = True
            Return
        End If
    End If

End Sub

C#:

C#:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if ((e.KeyChar == '.') && (((TextBox)sender).Text.IndexOf('.') > -1))
    {
        e.Handled = true;
        return;
    }

    if (!Char.IsDigit(e.KeyChar))
    {
        if ((e.KeyChar != '.') &&
            (e.KeyChar != Convert.ToChar(Keys.Back)))
        {
            e.Handled = true;
            return;
        }
    }
}

回答by Oliver

How about using Regex?

使用正则表达式怎么样?

This will validate a decimal number or whole number:

这将验证十进制数或整数:

VB

VB

If New Regex("^[\-]?\d+([\.]?\d+)?$").IsMatch(testString) Then
    'valid
End If

C#

C#

if (new Regex(@"^[\-]?\d+([\.]?\d+)?$").IsMatch(testString))
{
    //valid
}

回答by APrough

A little convoluted. Looks to make sure the character you just pressed is either numeric of a decimal and that there are no previous decimals.

有点纠结。看起来确保您刚刚按下的字符是小数的数字并且没有以前的小数。

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    If Char.IsDigit(e.KeyChar) Or (Asc(e.KeyChar) = Asc(".")) And Me.TextBox1.Text.Count(Function(c As Char) c = ".") = 0 Then e.Handled = False Else e.Handled = True
End Sub