我有以下代码,我想补充一点,它只允许在字符串中的任何位置添加一个小数点(句号)。
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
它只能接受数字,所以如何在这段代码中加入一个小数点?
由于
答案 0 :(得分: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;
}
}
}
答案 1 :(得分:2)
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
答案 2 :(得分:1)
如何使用Regex?
这将验证十进制数字或整数:
<强> VB 强>
If New Regex("^[\-]?\d+([\.]?\d+)?$").IsMatch(testString) Then
'valid
End If
<强> C#强>
if (new Regex(@"^[\-]?\d+([\.]?\d+)?$").IsMatch(testString))
{
//valid
}
答案 3 :(得分:0)
有点费解。看起来确保您按下的字符是小数的数字,并且没有先前的小数。
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