如何只允许文本框 vb.net 中的数字和点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11246198/
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
how to only allow digits and dots in textbox vb.net
提问by Christoph
i'm wondering how i can get my textbox to only accept digits and dots. like:
我想知道如何让我的文本框只接受数字和点。喜欢:
123.45 or 115 or 218.16978
123.45 或 115 或 218.16978
etc..
等等..
i allready got the following code:
我已经得到以下代码:
Private Sub TxtHStof_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtHStof.KeyPress
e.Handled = Not Char.IsDigit(e.KeyChar)
End Sub
But that only allows digits without the dots. How can i change the code so it does allows the dots aswell, but nothing else. (copy paste doesn't matter since it won't be an issue)
但这只允许没有点的数字。我如何更改代码,以便它也允许点,但没有别的。(复制粘贴无关紧要,因为它不会成为问题)
Thanks a lot
非常感谢
回答by Holger Brandt
e.Handled = Not (Char.IsDigit(e.KeyChar) OR e.KeyChar=".")
回答by Siddharth Rout
The accepted solution doesn't cater for
接受的解决方案不适合
- Multiple entries of decimals for example "12....1234"
- OS specific decimal separators
- 多个小数条目,例如“12....1234”
- 操作系统特定的小数点分隔符
This works for me
这对我有用
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
Dim DecimalSeparator As String = Application.CurrentCulture.NumberFormat.NumberDecimalSeparator
e.Handled = Not (Char.IsDigit(e.KeyChar) Or
Asc(e.KeyChar) = 8 Or
(e.KeyChar = DecimalSeparator And sender.Text.IndexOf(DecimalSeparator) = -1))
End Sub
回答by EkoostikMartin
You should use a MaskedTextBox
- see here on how to set the format string (which allows you to restrict to digits and decimal point only)
您应该使用MaskedTextBox
- 请参阅此处了解如何设置格式字符串(它允许您仅限制为数字和小数点)
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask.aspx
回答by Sudhakar MuthuKrishnan
'****To Allow only Numbers with Decimal and BACKSPACE enabled****
If Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = ".") And Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
回答by Jeroen van den Hondel
With this code you can use ',' (Europe) and '.' (American) decimals.
使用此代码,您可以使用“,”(欧洲)和“.” (美式)小数。
Private Sub TGewicht_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TGewicht.KeyPress
e.Handled = Not (Char.IsDigit(e.KeyChar) Or Asc(e.KeyChar) = 8 Or ((e.KeyChar = "." Or e.KeyChar = ",") And (sender.Text.IndexOf(".") = -1 And sender.Text.IndexOf(",") = -1)))
End Sub
回答by R.Alonso
Insert function in MODULE o FORM
在 MODULE o FORM 中插入函数
Public Sub OnlyNumber(Ct As TextBox, MaxLength As Integer)
Ct.MaxLength = MaxLength
AddHandler Ct.KeyPress, AddressOf ValidarTeclaNumeros
End Sub
Private Sub ValidarTeclaNumeros(sender As Object, e As KeyPressEventArgs)
Dim Ct As TextBox
Ct = sender
If [Char].IsDigit(e.KeyChar) OrElse [Char].IsControl(e.KeyChar) Then
'ok
'e.Handled = True
ElseIf [Char].IsPunctuation(e.KeyChar) Then
If (Ct.Text.Contains(",") OrElse Ct.Text.Contains(".")) Then
e.Handled = True
End If
Else
e.Handled = True
End If
End Sub
In load form add this code for your control only numerical (and only one comma or doc)
在加载表单中为您的控件添加此代码,仅数字(并且只有一个逗号或文档)
OnlyNumber(txtControl, 10)
回答by Zlosk
I started with mostly the same question, but I did care about being able to paste. While searching on the web for how to do this, I found that I really should handle:
我从大部分相同的问题开始,但我确实关心能够粘贴。在网上搜索如何做到这一点时,我发现我真的应该处理:
- Periods or commas as the decimal indicator, depending on how your OS is set up.
- Only allowing keypresses that conform to the pattern, while still allowing cursor control characters like arrows and backspace.
- Only allowing pastes into the TextBox that conform to the pattern. I chose to this in a manner that, when pasting, the code treats the pasted text as if the text was being keyed in, so pasting "a1b.c2d,e3f.g4h,i5j" into the TextBox would show up as "1.2345" if periods are your decimal indicator, and "12,345" if commas are your decimal indicator.
- 句点或逗号作为小数点指示符,具体取决于您的操作系统的设置方式。
- 只允许符合模式的按键,同时仍然允许光标控制字符,如箭头和退格。
- 只允许粘贴到符合模式的 TextBox 中。我选择的方式是,在粘贴时,代码将粘贴的文本视为已键入文本,因此将“a1b.c2d,e3f.g4h,i5j”粘贴到 TextBox 中将显示为“1.2345”如果句点是小数点指示符,“12,345”如果逗号是小数点指示符。
I tried the MaskedTextBox and really did not like it, as it enforced the decimal point location where I really just wanted to be able to freely fill in any numeric. I may have gone a little overboard using a RegEx for the pattern matching, but now I should be able to reuse this code pretty much anywhere.
我尝试了 MaskedTextBox 并且真的不喜欢它,因为它强制执行小数点位置,我真的只是希望能够自由填写任何数字。我使用正则表达式进行模式匹配可能有点过火,但现在我应该能够在几乎任何地方重用这段代码。
Public Class frmMain
Dim RegexValidator As System.Text.RegularExpressions.Regex
Dim FormLoaded As Boolean = False
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim RegexDecimalPattern As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
RegexDecimalPattern = IIf(RegexDecimalPattern = ".", "\.", RegexDecimalPattern)
RegexValidator = New System.Text.RegularExpressions.Regex("^\d*" & RegexDecimalPattern & "?\d*$", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
FormLoaded = True
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
' Code below is based on
' http://www.vbforums.com/showthread.php?626378-how-to-validate-textbox-allows-only-numeric-and-decimal-in-vb-net
' but was modified to be based on Regex patterns.
'
' Note that:
' KeyPress event validation covers data entry as it is being typed.
' TextChanged event validation covers data entry by cut/pasting.
If Char.IsControl(e.KeyChar) Then
'Allow all control characters.
Else
Dim Text = Me.TextBox1.Text
Dim SelectionStart = Me.TextBox1.SelectionStart
Dim SelectionLength = Me.TextBox1.SelectionLength
Text = Text.Substring(0, SelectionStart) & e.KeyChar & Text.Substring(SelectionStart + SelectionLength)
If Not RegexValidator.IsMatch(Text) Then e.Handled = True
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
' If default text is used in a textbox, a TextChanged event occurs before
' RegexValidator is initialized during the Form Load, so we need to check.
If FormLoaded Then
' Note that:
' KeyPress event validation covers data entry as it is being typed.
' TextChanged event validation covers data entry by cut/pasting.
Dim Text = Me.TextBox1.Text
Dim ValidatedText As String = ""
Dim KeyChar As Char
For Each KeyChar In Text
If RegexValidator.IsMatch(ValidatedText + KeyChar) Then ValidatedText += KeyChar
Next
If (ValidatedText.Length > 0) And (TextBox1.Text <> ValidatedText) Then
Me.TextBox1.Text = ValidatedText
Me.TextBox1.SelectionStart += ValidatedText.Length
End If
End If
End Sub
End Class
回答by Zlosk
Private Sub TextBox2_KeyPress(
ByVal sender As Object,
ByVal e As System.Windows.Forms.KeyPressEventArgs
) Handles TextBox2.KeyPress
e.Handled = Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = "." Or Asc(e.KeyChar) = 8)
End Sub
回答by tonyellard
Coming from C# and not VB, I'm taking a stab at this, but would this work:
来自 C# 而不是 VB,我正在尝试这一点,但这是否有效:
e.Handled = Not (Char.IsDigit(e.KeyChar) AndAlso e.KeyChar.Equals('.'))
回答by Jon Jewett
Just adding another solution. This code restricts user to entering only one "." decimal point, only two places beyond the decimal point, can set how many digits you want to use (currently I have it set to only allow up to to 5 whole numbers before the decimal. Also allows use of backspace and delete. That way they can't fat finger an extra "." and end up with something like "45.5.5".
只需添加另一个解决方案。此代码限制用户只能输入一个“.”。小数点,小数点后只有两位,可以设置你想要使用的位数(目前我将它设置为只允许小数点前最多 5 个整数。还允许使用退格和删除。这样他们不能胖手指一个额外的“。”并最终得到类似“45.5.5”的东西。
If Char.IsControl(e.KeyChar) Then
ElseIf Char.IsDigit(e.keyChar) OrElse e.keyChar = "."c Then
If Amount_FundedTextBox.TextLength = 5 And Amount_FundedTextBox.Text.Contains(".") = False Then
Amount_FundedTextBox.AppendText(".")
ElseIf e.KeyChar = "." And Amount_FundedTextBox.Text.IndexOf(".") <> -1 Then
e.Handled = True
ElseIf Char.IsDigit(e.KeyChar) Then
If Amount_FundedTextBox.Text.IndexOf(".") <> -1 Then
If Amount_FundedTextBox.Text.Length >= Amount_FundedTextBox.Text.IndexOf(".") + 3 Then
e.Handled = True
End If
End If
End If
Else
e.Handled = True
End If