我有以下代码,并希望添加一个事实,它只能允许在字符串中的任何位置添加一个小数点(句号)。
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
它只接受数字,那么我怎样才能在这段代码中加入一个小数点呢?
谢谢
我有以下代码,并希望添加一个事实,它只能允许在字符串中的任何位置添加一个小数点(句号)。
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
它只接受数字,那么我怎样才能在这段代码中加入一个小数点呢?
谢谢
该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
然而,虽然能够过滤掉无效的击键是件好事,但这样做存在很多问题。例如,即使进行了所有这些检查,仍然允许以下条目,即使它们很可能都应该是无效的:
另一个大问题是您的代码将依赖于文化。例如,在欧洲,通常使用逗号作为小数点。出于这些原因,如果可能,我建议Decimal.TryParse
在Validating
事件中简单地使用,如下所示:
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
解析字符串(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;
}
}
}
使用正则表达式怎么样?
这将验证十进制数或整数:
VB
If New Regex("^[\-]?\d+([\.]?\d+)?$").IsMatch(testString) Then
'valid
End If
C#
if (new Regex(@"^[\-]?\d+([\.]?\d+)?$").IsMatch(testString))
{
//valid
}
有点绕。看起来以确保您刚刚按下的字符是小数或小数,并且没有以前的小数。
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