【问题标题】:TextBox - Only allow Numeric and ONE full stop (representing a decimal number) VB.NET [duplicate]TextBox - 仅允许数字和一个句号(表示十进制数)VB.NET [重复]
【发布时间】:2013-03-14 13:38:17
【问题描述】:

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

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

它只接受数字,那么我如何在这段代码中加入一个小数点?

谢谢

【问题讨论】:

  • 另一个问题不允许只有数字。

标签: .net vb.net winforms visual-studio-2010


【解决方案1】:

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

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

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

至于检查多个小数点,你可以在按键事件中做一些事情,像这样:

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

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

  • 12.
  • 0000
  • 0001.

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

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

【讨论】:

    【解决方案2】:

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

    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#:

    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;
            }
        }
    }
    

    【讨论】:

    • 这不会只验证数值。
    • @Oliver:现在可以了。
    【解决方案3】:

    使用正则表达式怎么样?

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

    VB

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

    C#

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

    【讨论】:

    • 这是我要使用的方法,但是您的正则表达式有点损坏,因为应该允许 .32 (这是一个有效数字)。改用这个:^-?(\d*\.)?\d+$
    【解决方案4】:

    有点绕。看起来要确保您刚刚按下的字符是小数或小数,并且没有以前的小数。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      相关资源
      最近更新 更多