VB.net needs a text box to accept only numbers

I'm new to VB.net (self-taught) and I'm just wondering if anyone out there can help me with some code. I am not trying to do something too complicated, I just have a TextBox that accepts a numeric value from 1 to 10. I do not want it to accept a string or any number above 10. If someone enters a word or character, an error message will appear telling him to enter a valid number. This is what I have; obviously this is not so great as i have problems. Thanks again to everyone who can help.

  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() 
+22
numbers textbox
Apr 02 2018-12-12T00:
source share
26 answers

You can do this with Ascii integers. Put this code in the Keybox Keypress event. e.KeyChar represents the key pressed. And the built-in function Asc() converts it to its integer 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 
+25
Apr 02 2018-12-12T00:
source share

This is what I did to handle both key input and copy / paste.

 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 

If you want to allow decimal places, add

 AndAlso Not e.KeyChar = "." 

in the if statement in the KeyPress section.

+9
Apr 16 '15 at 19:17
source share

Try the following:

 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 
+5
Nov 13 '14 at 16:47
source share

You must first check if the input is an integer. You can do this with 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
Apr 02 2018-12-12T00:
source share

You can avoid any code by using the NumericUpDown control rather than a text field, this automatically resolves numbers and has a maximum and minimum. It also allows you to access the number directly using NumericUpDown1.Value , as well as use the up and down arrows to set the number. In addition, if a number above / above max is entered, it will go to the nearest allowed number.

+3
Apr 02 2018-12-12T00:
source share
 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 
+3
Jun 13
source share
 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 
+2
Jul 23 '14 at 11:08
source share
 Private Sub textBox5_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles textBox5.KeyPress 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 
+2
Aug 09 '17 at 10:07 on
source share
 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 
+1
May 6 '13 at
source share
 If Not Char.IsNumber(e.KeyChar) AndAlso Not e.KeyChar = "." AndAlso Not Char.IsControl(e.KeyChar) Then e.KeyChar = "" End If 

This allows you to use the delete key and set decimal points.

+1
Feb 07 '15 at 10:37
source share

I know this post is old, but I wanted to share what I implemented to turn a TextBox into what I call an IntBox.

First you need to do the extension with:

 <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 

Then create a TextChanged subtitle:

 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 

Then, whenever a user enters text, he evaluates the string and returns only numeric values ​​that are within the standard integer. With the β€œ-” symbol, you can change the integer from positive to negative and vice versa.

If anyone sees anything that might improve this code, let me know, but my tests show that it works fantastically to make IntBox.

EDIT: I found another method that might work if you use properties in your code. (Note that a separate property is required for TextBox)

First create a property:

 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 

Then bind in the main class of your window:

 Public WithEvents _YourVariable as New Properties Public Sub New() InitializeComponent() With YourTextBox .SetBinding(Textbox.TextProperty, New Binding("YourProperty")) .DataContext = _YourVariable End With End Sub 

Finally, here is the ToInteger extension code I installed:

 ''' <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 

When they are all combined, when they enter something into the field, it will act as if it were a text field, but when they change focus, the ToInteger extension sets the value as an integer to the property and returns it to the text field.

Considering that if the operator entered "-1w3" after changing the focus, he will automatically return to "-13".

+1
Dec 30 '15 at 13:54
source share

It may be too late, but for other new blood on VB there, there is something simple.

Firstly, in any case, if your application does not require it, blocking the user’s key input is somehow not very good, users may incorrectly interpret the action as a problem on the hardware keyboard and at the same time may not see where their key is Login error.

Here's a simple one, let the user freely enter their entry, and then delay the error later:

  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 
+1
Aug 13 '16 at 1:59
source share

The easiest solution to check in TextBox in VB.NET

TextBox Validation for Visual Basic (VB.NET)

First add a new VB code file to the project.

  • Go to Solution Explorer
  • Right click on your project
  • Select Add > New Item ...
  • Add a new VB code file (e.g. example.vb)

or press Ctrl + Shift + A

COPY and Paste the code into this file and give it a suitable name. (i.e. 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 

Now use the following code for the form load event, as shown below.

 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 

Done! ..

+1
Aug 25 '17 at 18:18
source share

First of all, set the TextBox MaxLength to 2, which will limit the number of text entries in your TextBox . Then you can try something similar using KeyPress Event . Since you are using a maximum of 2 digits (10), you will need to use a Key , such as Enter , to start checking.

 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 
0
Apr 02 '12 at 3:20
source share

You can use the following code. Text field. Key Press 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 

This code allows only numbers, and you can enter only a number from 1 to 10.

0
Apr 02 2018-12-12T00:
source share
 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 
0
Feb 06 '13 at 19:45
source share

You can use the onkeydown property for a TextBox to limit its value to numbers only.

 <asp:TextBox ID="TextBox1" runat="server" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32);"></asp:TextBox> 

! (keyCode> = 65) validation is performed for exclusive alphabets.

keyCode! = 32 check is designed to exclude the space character between numbers.

If you also want to exclude characters from entering text field, include the condition below also in the "onkeydown" property.

 !(event.shiftKey && (event.keyCode >= 48 && event.keyCode <= 57)) 

So the TextBox will finally become

 <asp:TextBox ID="TextBox1" runat="server" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32 && !(event.shiftKey && (event.keyCode >= 48 && event.keyCode <= 57)));"></asp:TextBox> 

Explanation:

KeyCode for 'a' is '65', and 'z' is '90'.

Key codes '90' to '222', which are other characters, are also not needed.

KeyCode for "Space" Key - "32", which is also not needed.

Then the key combination "Shift" and "Number" (denoting characters) is also not needed. KeyCode for β€œ0” is β€œ48” and β€œ9” is β€œ57”.

Therefore, they are all included in the TextBox declaration itself, which gives the desired result.

Try and see.

0
May 28 '15 at 5:50
source share

This worked for me ... just clear the text box completely by pressing non-numeric keys.

 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 
0
Jun 04 '15 at 23:07
source share

Copy this function to any module inside your vb.net project.

 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 

Then use this function inside your textbox_keydown event, as shown below:

 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 

And yes. It works 100% :)

0
Aug 26 '15 at 12:50
source share

This was my final ... This applies to all problems like:

Here is a simple text field that requires a number:

  public Sub textbox_memorytotal_TextChanged(sender As Object, e As EventArgs) Handles textbox_memorytotal.TextChanged TextboxOnlyNumbers(sender) End Sub 

and here is the procedure that fixes all bad input:

 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 
0
Jun 26 '16 at 20:26
source share

Use this in your Keybox Keydown event.

 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 

Copy this function to any module inside your vb.net project.

 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 not a number. If Control.ModifierKeys = Keys.Shift Then nonNumberEntered = True End If End Function 

This will allow you to enter numbers, such as 2/4, or numbers, such as 3.5, in your text box if decim is used "nonNumberEntered (e, Textbox1, True)".

Allows you to enter only numbers in a text field using "nonNumberEntered (e, Textbox1, False)" or "nonNumberEntered (e, Textbox1)".

Edit: added text.

0
04 Oct '16 at 16:47
source share

Recently, I had a similar use for a TextBox that could only accept numbers.

In the end, I used MaskedTextBox instead of TextBox . You define a β€œmask” for the text field, and it will only accept the characters that you define β€” in this case, numbers. The downside is that it leaves a slightly ugly line inside the TextBox ;

Text mask

What I loved about MaskedTextBox was so customizable. If for some reason you would like the TextBox accept only input in 3 int format and then 2 letters, all you have to do is set TextMask to 000LL . Visual Studio has predefined masks loaded, and full documentation can be found here .

Predefined masks

Now I know that this does not completely solve your problem, but using MaskedTextBox eliminates a huge part of the complexity of the problem. Now you can guarantee that the contents of MaskedTextBox will only ever be Int , which allows you to run a simple If statement to provide a value =<10

0
Oct 31 '16 at 0:07
source share

I know this post is old, but I want to share my code.

  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 
0
Mar 31 '17 at 8:03
source share

In each entry in the text field (event - Handles RestrictedTextBox.TextChanged), you can try to cast the entered text into an integer, if it fails, you simply reset the text value in the RestrictedTextBox for the last valid input (which is constantly updated under the variable temp1).

Here's how to do it. In sub, which loads with the form (me.load or mybase.load), initializes temp1 with the default value 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 

At any other point in the form:

 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 

The nice thing is that you can use this to restrict the text field to any type you want: double, uint etc ....

0
Jul 30 '17 at 0:54
source share

each text field has a validating and verified event that you can use as follows: -

 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 
0
Sep 21 '17 at 15:52
source share
 Imports System.Drawing Imports System.Text.RegularExpressions Imports System.Windows.Forms Module Module1 Public Enum ValidationType MaxMin = 1 End Enum Public Sub AssignValidation(ByRef CTRL As TextBox, ByVal Validation_Type As ValidationType, Min As Double, Max As Double) Dim txt As TextBox = CTRL Select Case Validation_Type Case ValidationType.MaxMin AddHandler txt.TextChanged, AddressOf MaximumMinimum End Select End Sub Public Sub MaximumMinimum(ByVal sender As Object, ByVal e As System.EventArgs) Dim NO As TextBox = sender If Val(NO.Text) < Min Then NO.Focus() ElseIf Val(NO.Text) > Max Then NO.Focus() End If End Sub End Module 

I have a question about this code. , , ?

0
09 . '18 23:31
source share



All Articles