我知道以下代码会阻止usser在文本框中使用空格但是如何让用户只使用numbbers和fulstop(所以我可以添加1.5之类的值)
Private Sub Textbox4_keyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox4.KeyDown
If e.KeyCode = Keys.Space Then
TextBox4.Clear()
MsgBox("Invalid character. No spaces Permited...")
End If
答案 0 :(得分:2)
从可用性的角度来看,在KeyDown
事件中测试有效输入并不好。例如,当用户想要将文本粘贴到文本框中时会发生什么?
此外,用户仍然可以使用TextBox的上下文菜单粘贴无效输入,您的代码不会注意到这一点。
您应该允许所有输入,然后在用户离开文本框时测试其有效性。 VB有一个额外的事件,只要文本框失去焦点就会触发:Validating
。使用此事件(以及仅此事件)来测试有效输入。
答案 1 :(得分:0)
一个简单的方法可能是查找“允许”字符,如果不是其中之一,则显示错误消息。
答案 2 :(得分:0)
在编写代码的最近20年中,我总是对TextBoxes Check Characters使用以下基本原理
首先,您必须创建一个单独的类,您可以将其称为(为方便起见)Char_Validation
在这个类的内部,你将放置一个返回布尔值的函数,如下所示。
Public Class Char_Validation
Public Const Gr As String = "Greek"
Public Const En As String = "English"
Public Const Num As String = "Numbers"
Public Const FullGr As String = "Full Greek"
Public Const FullEn As String = "Full English"
Public Const EnN As String = "English with Numbers"
Public Const GrN As String = "Greek with Numbers"
Public Shared Function ValidateChar(ByVal AsciiChar As String, ByVal CharTable As String, ByVal sender As Object, ByVal e As System.EventArgs) As Boolean
Dim ConvChar As Integer = CUInt(Microsoft.VisualBasic.Asc(AsciiChar))
Dim ConvCharW As Integer = CUInt(Microsoft.VisualBasic.AscW(AsciiChar))
ValidateChar = False
Select Case CharTable
Case En
Select Case ConvChar
Case 65 To 126, 145 To 150, 8, 32 To 47, 58 To 64, 128, 130
ValidateChar = True
End Select
Case EnN
Select Case ConvChar
Case 48 To 57, 65 To 126, 8, 32, 45
ValidateChar = True
End Select
.
.
.
.
.
Case Num
Select Case ConvChar
Case 44 To 57, 92, 8
ValidateChar = True
End Select
End Select
End Function
End Class
在Form in Class中,您将使用TextBox_KeyPress,您将使用以下代码。
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
ErrorProvider1.Clear()
ErrorLabel.ForeColor = Drawing.Color.Black
Select Case Char_Validation.ValidateChar(e.KeyChar, Char_Validation.Num, sender, e)
Case True
Case False
ErrorProvider1.SetError(TextBox1, "Wrong Character Only Numbers")
Beep()
e.KeyChar = ""
End Select
End Sub
因此,您将禁止用户将字符置于您的决定之外
我希望从现在起,这将涵盖你。
答案 3 :(得分:0)
以下代码适用于我:firefox,IE 8,chrome,Safari和iphone。
function dotplaced(myfield){
如果(myfield.indexOf()=== “” - 1){
返回false;
}
返回true;
}
functionOnly(myfield,e){
var键;
var keychar;
if (window.event) {
key = window.event.keyCode;
}
else if (e) {
key = e.which;
}
else {
return true;
}
keychar = String.fromCharCode(key);
// control keys
if ((key == null) || (key == 0) || (key == 8) ||
(key == 9) || (key == 13) || (key == 27)) {
return true;
}
// numbers
else if ((("0123456789").indexOf(keychar) > -1)) {
return true;
}
// decimal point jump
else if (!dotplaced(myfield.value) && (keychar == ".")) {
//myfield.form.elements[dec].focus();
return true;
}
else {
return false;
}
}