我是VB.net的新手(自学成才),只是想知道是否有人可以帮我解决一些代码问题。我不是要做任何太多涉及的事情,只是让TextBox
接受1到10之间的数值。我不希望它接受一个字符串或任何高于10的数字。如果有人输入一个单词或字符将出现错误消息,告诉他输入有效的数字。这就是我的意思;显然它不是很好,因为我有问题。再次感谢任何可以提供帮助的人。
If TxtBox.Text > 10 Then
MessageBox.Show("Please Enter a Number from 1 to 10")
TxtBox.Focus()
ElseIf TxtBox.Text < 10 Then
MessageBox.Show("Thank You, your rating was " & TxtBox.Text)
Total = Total + 1
ElseIf IsNumeric(TxtBox.Text) Then
MessageBox.Show("Thank you, your rating was " & ValueTxtBox.Text)
End If
ValueTxtBox.Clear()
ValueTxtBox.Focus()
答案 0 :(得分:30)
您可以使用Ascii整数执行此操作。将此代码放在Textbox的Keypress事件中。 e.KeyChar
表示按下的键。并且内置函数Asc()
将其转换为其Ascii整数。
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
'97 - 122 = Ascii codes for simple letters
'65 - 90 = Ascii codes for capital letters
'48 - 57 = Ascii codes for numbers
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
答案 1 :(得分:11)
这是我为了处理键输入和复制/粘贴而做的。
Private Sub TextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox.KeyPress
If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
End Sub
Private Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox.TextChanged
Dim digitsOnly As Regex = New Regex("[^\d]")
TextBox.Text = digitsOnly.Replace(TextBox.Text, "")
End Sub
如果要允许小数,请添加
AndAlso Not e.KeyChar = "."
到KeyPress部分的if语句。
答案 2 :(得分:6)
试试这个:
Private Sub txtCaseID_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtCaseID.KeyPress
If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then e.KeyChar = ""
End Sub
答案 3 :(得分:4)
您必须首先验证输入实际上是否为整数。您可以使用Integer.TryParse
:
Dim intValue As Integer
If Integer.TryParse(TxtBox.Text, intValue) AndAlso intValue > 0 AndAlso intValue < 11 Then
MessageBox.Show("Thank You, your rating was " & TxtBox.Text)
Else
MessageBox.Show("Please Enter a Number from 1 to 10")
End If
答案 4 :(得分:3)
您可以通过使用NumericUpDown控件而不是文本框来避免任何代码,这自动只允许数字并具有最大值和最小值。
它还允许使用NumericUpDown1.Value
直接访问号码,以及使用向上和向下箭头设置号码。
此外,如果输入的数字高于/超过最大值,它将跳转到最接近的允许数字。
答案 5 :(得分:3)
Private Sub MyTextBox_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles MyTextBox.KeyPress
If Not IsNumeric(e.KeyChar) And Not e.KeyChar = ChrW(Keys.Back) Then
e.Handled = True
End If
End Sub
答案 6 :(得分:2)
Private Sub Data_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Data.KeyPress
If (Not e.KeyChar = ChrW(Keys.Back) And ("0123456789.").IndexOf(e.KeyChar) = -1) Or (e.KeyChar = "." And Data.Text.ToCharArray().Count(Function(c) c = ".") > 0) Then
e.Handled = True
End If
End Sub
答案 7 :(得分:2)
steps
答案 8 :(得分:1)
这可能为时已晚,但对于VB上的其他新血,这里有点简单。
首先,在任何情况下,除非您的应用程序需要,否则阻止用户的密钥输入在某种程度上不是一件好事,用户可能会将操作误解为硬件键盘上的问题,同时可能看不到他们的密钥被切断的位置输入错误来自。
这是一个简单的问题,让用户自由输入他们的条目,然后再捕获错误:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim theNumber As Integer
Dim theEntry As String = Trim(TextBox1.Text)
'This check if entry can be converted to
'numeric value from 0-10, if cannot return a negative value.
Try
theNumber = Convert.ToInt32(theEntry)
If theNumber < 0 Or theNumber > 10 Then theNumber = -1
Catch ex As Exception
theNumber = -1
End Try
'Trap for the valid and invalid numeric number
If theNumber < 0 Or theNumber > 10 Then
MsgBox("Invalid Entry, allows (0-10) only.")
'entry was invalid return cursor to entry box.
TextBox1.Focus()
Else
'Entry accepted:
' Continue process your thing here...
End If
End Sub
答案 9 :(得分:1)
Dim ch(10) As Char
Dim len As Integer
len = TextBox1.Text.Length
ch = TextBox1.Text.ToCharArray()
For i = 0 To len - 1
If Not IsNumeric(ch(i)) Then
MsgBox("Value you insert is not numeric")
End If
Next
答案 10 :(得分:1)
If Not Char.IsNumber(e.KeyChar) AndAlso Not e.KeyChar = "." AndAlso Not Char.IsControl(e.KeyChar) Then
e.KeyChar = ""
End If
这允许您使用删除键并设置小数点
答案 11 :(得分:1)
首先,在项目中添加新的VB代码文件。
或按 Ctrl + Shift + A
COPY&amp;将代码粘贴到此文件中并为其指定合适的名称。 (即KeyValidation.vb)
Imports System.Text.RegularExpressions
Module Module1
Public Enum ValidationType
Only_Numbers = 1
Only_Characters = 2
Not_Null = 3
Only_Email = 4
Phone_Number = 5
End Enum
Public Sub AssignValidation(ByRef CTRL As Windows.Forms.TextBox, ByVal Validation_Type As ValidationType)
Dim txt As Windows.Forms.TextBox = CTRL
Select Case Validation_Type
Case ValidationType.Only_Numbers
AddHandler txt.KeyPress, AddressOf number_Leave
Case ValidationType.Only_Characters
AddHandler txt.KeyPress, AddressOf OCHAR_Leave
Case ValidationType.Not_Null
AddHandler txt.Leave, AddressOf NotNull_Leave
Case ValidationType.Only_Email
AddHandler txt.Leave, AddressOf Email_Leave
Case ValidationType.Phone_Number
AddHandler txt.KeyPress, AddressOf Phonenumber_Leave
End Select
End Sub
Public Sub number_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Dim numbers As Windows.Forms.TextBox = sender
If InStr("1234567890.", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
e.KeyChar = Chr(0)
e.Handled = True
End If
End Sub
Public Sub Phonenumber_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Dim numbers As Windows.Forms.TextBox = sender
If InStr("1234567890.()-+ ", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
e.KeyChar = Chr(0)
e.Handled = True
End If
End Sub
Public Sub OCHAR_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
If InStr("1234567890!@#$%^&*()_+=-", e.KeyChar) > 0 Then
e.KeyChar = Chr(0)
e.Handled = True
End If
End Sub
Public Sub NotNull_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
Dim No As Windows.Forms.TextBox = sender
If No.Text.Trim = "" Then
MsgBox("This field Must be filled!")
No.Focus()
End If
End Sub
Public Sub Email_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Email As Windows.Forms.TextBox = sender
If Email.Text <> "" Then
Dim rex As Match = Regex.Match(Trim(Email.Text), "^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,3})$", RegexOptions.IgnoreCase)
If rex.Success = False Then
MessageBox.Show("Please Enter a valid Email Address", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
Email.BackColor = Color.Red
Email.Focus()
Exit Sub
Else
Email.BackColor = Color.White
End If
End If
End Sub
End Module
现在使用以下代码进行表单加载事件,如下所示。
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AssignValidation(Me.TextBox1, ValidationType.Only_Digits)
AssignValidation(Me.TextBox2, ValidationType.Only_Characters)
AssignValidation(Me.TextBox3, ValidationType.No_Blank)
AssignValidation(Me.TextBox4, ValidationType.Only_Email)
End Sub
完成..!
答案 12 :(得分:1)
我知道这篇文章很老但我想分享一些我已经实现的东西,将TextBox变成我称之为IntBox的东西。
首先,您需要使用以下内容进行扩展:
<Runtime.CompilerServices.Extension()> _
Public Function HandledStringtoInteger(s As String) As Integer
Try
If s = String.Empty Then
Return 0
Else
Return Integer.Parse(s)
End If
Catch
Dim result As String = String.Empty
Dim ReturnInt As Integer
Dim Parsed As Integer
For Each Character In s.ToCharArray
If Character = "-" Then
If s.Substring(0, 1).ToString <> "-" Then
result = Character + result
End If
End If
If Character = "." Then
Exit For
End If
If Integer.TryParse(Character, Parsed) Then
result = result + Parsed.ToString
End If
Next
If result <> String.Empty Then
If Integer.TryParse(result, ReturnInt) Then
Return Integer.Parse(ReturnInt)
Else
If Double.Parse(result) > Double.Parse(Integer.MaxValue.ToString) Then
Return Integer.MaxValue
ElseIf Double.Parse(result) < Double.Parse(Integer.MinValue.ToString) Then
Return Integer.MinValue
Else
Return Integer.Parse(ReturnInt)
End If
End If
Else
Return 0
End If
End Try
End Function
然后创建一个TextChanged事件子:
Private Sub TextBox_to_IntBox(sender As Object, e As TextChangedEventArgs) Handles YourTextBox.TextChanged
If DirectCast(sender, TextBox).IsKeyboardFocused Then
DirectCast(sender, TextBox).Text = DirectCast(sender, TextBox).Text.HandledStringtoInteger
DirectCast(sender, TextBox).CaretIndex = DirectCast(sender, TextBox).Text.Length
End If
End Sub
然后,只要用户输入文本,它就会计算字符串,并仅返回标准Integer范围内的数值。使用“ - ”字符,您可以将整数从正数更改为负数再返回。
如果有人看到任何可以改进此代码的内容,请告诉我,但我的测试显示这对于制作IntBox非常有用。
编辑: 我找到了另一种方法,如果你在代码中使用属性,它可以工作。 (注意,每个TextBox需要一个单独的属性)
首先创建属性:
Public Class Properties
Implement INotifyPropertyChanged
Private _Variable as Integer
Public Property YourProperty as Object
get
Return _Variable
end get
set(value as Object)
_Variable = value.ToString.ToInteger 'I will give the ToInteger extension code later
end set
end property
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Public Sub OnPropertyChange(ByVal e As PropertyChangedEventArgs)
If Not PropertyChangedEvent Is Nothing Then
RaiseEvent PropertyChanged(Me, e)
End If
End Sub
End Class
然后在窗口的主类中进行绑定:
Public WithEvents _YourVariable as New Properties
Public Sub New()
InitializeComponent()
With YourTextBox
.SetBinding(Textbox.TextProperty, New Binding("YourProperty"))
.DataContext = _YourVariable
End With
End Sub
最后,我设置了ToInteger扩展代码:
''' <summary>
''' Handles conversion of variable to Integer.
''' </summary>
''' <param name="X"></param>
''' <param name="I">Returned if conversion fails.</param>
''' <returns>Signed 32bit Integer</returns>
''' <remarks></remarks>
<Runtime.CompilerServices.Extension()> _
Public Function toInteger(Of T)(ByRef X As T, Optional I As Integer = 0) As Integer
Dim S As String = X.ToString
Try
If S = String.Empty Then
Return I
Else
Return Integer.Parse(S)
End If
Catch
Dim result As String = String.Empty
Dim ReturnInt As Integer
Dim Parsed As Byte
For Each Character In S.ToCharArray
If Character = "-" Then
If S.Substring(0, 1).ToString <> "-" Then
result = Character + result
End If
End If
If Character = "." Then
Exit For
End If
If Byte.TryParse(Character, Parsed) Then
result = result + Parsed.ToString
End If
Next
If result <> String.Empty Then
If Integer.TryParse(result, ReturnInt) Then
Return Integer.Parse(ReturnInt)
Else
If Double.Parse(result) > Double.Parse(Integer.MaxValue.ToString) Then
Return Integer.MaxValue
ElseIf Double.Parse(result) < Double.Parse(Integer.MinValue.ToString) Then
Return Integer.MinValue
Else
Return Integer.Parse(ReturnInt)
End If
End If
Else
Return I
End If
End Try
End Function
将所有这些组合在一起,只要它们在框中输入内容,它就会像文本框一样,但当它们改变焦点时,ToInteger扩展会将值设置为属性并将其返回到文本框。
意思是如果操作员在焦点改变后输入“-1w3”,它将自动返回为“-13”。
答案 13 :(得分:0)
我知道这篇文章很老但我想分享我的代码。
Private Sub txtbox1_TextChanged(sender As Object, e As EventArgs) Handles txtbox1.TextChanged
If txtbox1.Text.Length > 0 Then
If Not IsNumeric(txtbox1.Text) Then
Dim sel As Integer = txtbox1.SelectionStart
txtbox1.Text = txtbox1.Text.Remove(sel - 1, 1)
txtbox1.SelectionStart = sel - 1
End If
End If
End Sub
答案 14 :(得分:0)
这对我有用......只需按下非数字键即可完全清除文本框。
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
If IsNumeric(TextBox2.Text) Then
'nada
Else
TextBox2.Clear()
End If
End Sub
答案 15 :(得分:0)
在文本框中的每个条目(事件 - Handles RestrictedTextBox.TextChanged)中,您可以尝试将输入的文本分成整数,如果发生故障,您只需将RestrictedTextBox中的文本值重置为上一个有效条目(获取在temp1变量下不断更新。
以下是如何解决这个问题。在使用表单(me.load或mybase.load)加载的sub中,将temp1初始化为RestrictedTextBox.Text的默认值
Dim temp1 As Integer 'initialize temp1 default value, you should do this after the default value for RestrictedTextBox.Text was loaded.
If (RestrictedTextBox.Text = Nothing) Then
temp1 = Nothing
Else
Try
temp1 = CInt(RestrictedTextBox.Text)
Catch ex As Exception
temp1 = Nothing
End Try
End If
在表格的任何其他方面:
Private Sub textBox_TextChanged(sender As System.Object, e As System.EventArgs) Handles RestrictedTextBox.TextChanged
Try
temp1 = CInt(RestrictedTextBox.Text) 'If user inputs integer, this will succeed and temp will be updated
Catch ex As Exception
RestrictedTextBox.Text = temp1.ToString 'If user inputs non integer, textbox will be reverted to state the state it was in before the string entry
End Try
End Sub
关于这一点的好处是你可以使用它来将文本框限制为你想要的任何类型:double,uint等....
答案 16 :(得分:0)
每个文本框都有一个验证和验证事件,您可以按如下方式使用: -
Private Sub PriceTxt_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles PriceTxt.Validating
If Not IsNumeric(PriceTxt.Text) Then
PriceTxt.BackColor = Color.Red
MsgBox("The Price Should Be Numeric Only , Enter Again", vbCritical)
PriceTxt.Text = ""
PriceTxt.BackColor = Color.White
End If
End Sub
答案 17 :(得分:0)
我知道它已经很旧了。为了方便起见,我将这段代码留在这里。
仅整数:
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
With TextBox1
If IsNumeric(.Text) Then .Text = .Text.Select(Function(x) If(IsNumeric(x), x, "")) : .SelectionStart = .TextLength
End With
' etc..
End Sub
接受Double
:
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
With TextBox1
If IsNumeric(.Text) Then .Text = .Text.Select(Function(x) If(IsNumeric(x) Or x = ".", x, "")) : .SelectionStart = .TextLength
End With
' etc..
End Sub
接受基本操作+ - * /
,括号( ) [ ] { }
和Double
:
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
With TextBox1
If IsNumeric(.Text) Then .Text = .Text.Select(Function(x) If(IsNumeric(x) Or ".+-*/()[]{}".Contains(x), x, "")) : .SelectionStart = .TextLength
End With
' etc..
End Sub
答案 18 :(得分:0)
非常简单的一段代码,对我有用。
Private Sub Textbox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textbox1.KeyPress
If Asc(e.KeyChar) > 58 Then
e.KeyChar = ""
End If
End Sub
答案 19 :(得分:0)
我最近对TextBox
有一个类似的使用要求,它只能取数字。
最后我使用了MaskedTextBox
而不是TextBox
。你定义一个&#34;掩码&#34;对于文本框,它只接受您定义的字符 - 在本例中为数字。缺点是它在TextBox
;
我对MaskedTextBox
所喜爱的是它是如此可定制的。如果您出于某种原因希望TextBox
仅接受3个整数后跟2个字母的输入,则您需要做的就是将TextMask
设置为000LL
。 Visual Studio中有大量预定义的掩码,可以找到完整的文档here。
现在,我知道这并没有完全解决您的问题,但MaskedTextBox
的使用消除了问题复杂性的很大一部分。您现在可以保证MaskedTextBox
的内容只能是Int
,这样您就可以运行简单的If
语句,以确保值为=<10
答案 20 :(得分:0)
在Textbox Keydown事件中使用它。
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
'you can enter decimal "if nonNumberEntered(e, TextBox1, True) then"
'otherwise just numbers "if nonNumberEntered(e, TextBox1) then"
If nonNumberEntered(e, TextBox1, True) Then
e.SuppressKeyPress = True
End If
If e.KeyCode = Keys.Enter Then
'put your code here
End If
End Sub
将此功能复制到vb.net项目中的任何模块中。
Public Function nonNumberEntered(ByVal e As System.Windows.Forms.KeyEventArgs, _
ByVal ob As TextBox, _
Optional ByVal decim As Boolean = False) As Boolean
nonNumberEntered = False
If decim Then
' Determine whether the keystroke is a number from the top of the keyboard.
If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
' Determine whether the keystroke is a number from the keypad.
If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
If e.KeyCode <> Keys.Decimal And e.KeyCode <> Keys.OemPeriod Then
If e.KeyCode <> Keys.Divide And e.KeyCode <> Keys.OemQuestion Then
' Determine whether the keystroke is a backspace.
If e.KeyCode <> Keys.Back And e.KeyCode <> Keys.Delete _
And e.KeyCode <> Keys.Left And e.KeyCode <> Keys.Right Then
' A non-numerical keystroke was pressed.
nonNumberEntered = True
End If
ElseIf ob.Text.Contains("/") Or ob.Text.Length = 0 Then
nonNumberEntered = True
End If
ElseIf ob.Text.Contains(".") Or ob.Text.Length = 0 Then
nonNumberEntered = True
End If
End If
End If
Else
' Determine whether the keystroke is a number from the top of the keyboard.
If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
' Determine whether the keystroke is a number from the keypad.
If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
' Determine whether the keystroke is a backspace.
If e.KeyCode <> Keys.Back And e.KeyCode <> Keys.Delete _
And e.KeyCode <> Keys.Left And e.KeyCode <> Keys.Right Then
' A non-numerical keystroke was pressed.
nonNumberEntered = True
End If
End If
End If
End If
'If shift key was pressed, it's not a number.
If Control.ModifierKeys = Keys.Shift Then
nonNumberEntered = True
End If
End Function
如果使用decim“nonNumberEntered(e,Textbox1,True)”,这将允许在文本框中输入像2/4或数字这样的数字。
如果使用“nonNumberEntered(e,Textbox1,False)”或“nonNumberEntered(e,Textbox1)”,则只允许在文本框中输入数字。
编辑:添加文字。
答案 21 :(得分:0)
这是我的最终......它解决了所有类型问题:
这是一个简单的文本框,需要一个数字:
public Sub textbox_memorytotal_TextChanged(sender As Object, e As EventArgs) Handles textbox_memorytotal.TextChanged
TextboxOnlyNumbers(sender)
End Sub
这是纠正所有错误输入的过程:
Public Sub TextboxOnlyNumbers(ByRef objTxtBox As TextBox)
' ONLY allow numbers
If Not IsNumeric(objTxtBox.Text) Then
' Don't process things like too many backspaces
If objTxtBox.Text.Length > 0 Then
MsgBox("Numerical Values only!")
Try
' If something bad was entered delete the last character
objTxtBox.Text = objTxtBox.Text.Substring(0, objTxtBox.Text.Length - 1)
' Put the cursor and the END of the corrected number
objTxtBox.Select(objTxtBox.Text.Length + 1, 1)
Catch ex As Exception
End Try
End If
End If
End Sub
答案 22 :(得分:0)
将此功能复制到vb.net项目中的任何模块中。
Public Function MakeTextBoxNumeric(kcode As Integer, shift As Boolean) As Boolean
If kcode >= 96 And kcode <= 105 Then
ElseIf kcode >= 48 And kcode <= 57
If shift = True Then Return False
ElseIf kcode = 8 Or kcode = 107 Then
ElseIf kcode = 187 Then
If shift = False Then Return False
Else
Return False
End If
Return True
End Function
然后在textbox_keydown事件中使用此函数,如下所示:
Private Sub txtboxNumeric_KeyDown(sender As Object, e As KeyEventArgs) Handles txtboxNumeric.KeyDown
If MakeTextBoxNumeric(e.KeyCode, e.Shift) = False Then e.SuppressKeyPress = True
End Sub
是的。它100%工作:)
答案 23 :(得分:0)
您可以使用TextBox的 onkeydown 属性将其值仅限制为数字。
<asp:TextBox ID="TextBox1" runat="server" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32);"></asp:TextBox>
!(keyCode&gt; = 65)检查是否为排除的字母。
keyCode!= 32 检查是否在数字之间排除空格字符。
如果您想要排除符号也不要进入文本框,那么也请在'onkeydown'属性中包含以下条件。
!(event.shiftKey && (event.keyCode >= 48 && event.keyCode <= 57))
因此TextBox最终将成为
<asp:TextBox ID="TextBox1" runat="server" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32 && !(event.shiftKey && (event.keyCode >= 48 && event.keyCode <= 57)));"></asp:TextBox>
<强> 说明: 强>
'a'的KeyCode是'65','z'是'90'。
从'90'到'222'的KeyCodes也是不需要的其他符号。
'Space'键的KeyCode为'32',也不需要。
然后也不需要'Shift'键和'Number'键(表示符号)的组合。 '0'的KeyCode是'48','9'是'57'。
因此,所有这些都包含在TextBox声明本身中,从而产生所需的结果。
试试看。
答案 24 :(得分:0)
Public Function Isnumber(ByVal KCode As String) As Boolean
If Not Isnumeric(KCode) And KCode <> ChrW(Keys.Back) And KCode <> ChrW(Keys.Enter) And KCode <> "."c Then
MsgBox("Please Enter Numbers only", MsgBoxStyle.OkOnly)
End If
End Function
Private Sub txtBalance_KeyPress(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles txtBalance.KeyPress
If Not Isnumber(e.KeyChar) Then
e.KeyChar = ""
End If
End Sub
答案 25 :(得分:0)
您可以使用Follow code Textbox Keypress Event:
Private Sub txtbox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtbox1.KeyPress
Try
If val(txtbox1.text) < 10 then
If Char.IsLetterOrDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If
Else
e.Handled = True
End If
Catch ex As Exception
ShowException(ex.Message, MESSAGEBOX_TITLE, ex)
End Try
End Sub
此代码仅允许数字,您只能输入1到10之间的数字。
答案 26 :(得分:0)
首先将TextBox的MaxLength
设置为2,这将限制TextBox
中的文本输入量。然后你可以使用KeyPress Event
尝试这样的事情。由于您使用的是最多2位数(10),因此您需要使用Key
(例如Enter
)来启动检查。
Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim tb As TextBox = CType(sender, TextBox)
If Not IsNumeric(e.KeyChar) Then 'Check if Numeric
If Char.IsControl(e.KeyChar) Then 'If not Numeric Check if a Control
If e.KeyChar = ChrW(Keys.Enter) Then
If Val(tb.Text) > 10 Then 'Check Bounds
tb.Text = ""
ShowPassFail(False)
Else
ShowPassFail(True)
End If
e.Handled = True
End If
Exit Sub
End If
e.Handled = True
ShowPassFail(False)
End If
End Sub
Private Sub ShowPassFail(pass As Boolean)
If pass Then
MessageBox.Show("Thank you, your rating was " & TextBox1.Text)
Else
MessageBox.Show("Please Enter a Number from 1 to 10")
End If
TextBox1.Clear()
TextBox1.Focus()
End Sub