limit the range of characters the user can put into a textbox vb.net - vb.net

I have a textbox in a vb form and I want to limit the range of characters that the user can put into the textbox to:" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*().". The textbox is to insert SI Units into a database so i need consistent syntax. If the user types an invalid character into the textbox I would like the textbox to refuse to insert it, or remove it straight away, leaving the cursor in the same position within the textbox. I would also like the textbox to replace "/" with "^(-" and place the cursor before this.
I have found some code elsewhere which I have edited to do this but the code is bad, it activates on text changed within the textbox. This causes the code to fail, when the user inputs a disallowed value the code it activates itself when it tries to changes the text within the textbox.
Here is my code, the textbox starts with the contents "enter SI Units" from the form designer.
Private Sub TxtQuantityTextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSIUnit.TextChanged
If txtSIUnit.Text = "Enter SI Units" Then
Exit Sub
End If
Dim charactersAllowed As String = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*()."
Dim Text As String = txtSIUnit.Text
Dim Letter As String
Dim SelectionIndex As Integer = txtSIUnit.SelectionStart
Dim Change As Integer
Letter = txtSIUnit.Text.Substring(SelectionIndex - 1, 1)
If Letter = "/" Then
Text = Text.Replace(Letter, "^(-")
SelectionIndex = SelectionIndex - 1
End If
Letter = txtSIUnit.Text.Substring(SelectionIndex - 1, 1)
If charactersAllowed.Contains(Letter) = False Then
Text = Text.Replace(Letter, String.Empty)
Change = 1
End If
txtSIUnit.Text = Text
txtSIUnit.Select(SelectionIndex - Change, 0)
If txtQuantity.Text <> "Enter Quantity" Then
If cmbStateRateSumRatio.SelectedIndex <> -1 Then
bttAddQUAtoDatabase.Enabled = True
End If
End If
End Sub`
Thanks for you help.

Use the KeyPress event. Set e.Handled to true if you don't like the character. It's a one-liner:
Private Const AllowedChars = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*()."
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As PressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar >= " "c AndAlso Not AllowedChars.Contains(e.KeyChar) Then e.Handled = True
End Sub

In the textbox's KeyDown event, check e.KeyCode. This lets you prevent certain characters from being handled. There's an example on the KeyDown documentation.

Related

Only show a certain count of textboxes in vb.net

I'm trying to make several TextBoxes visible and invisible, depending on the number in another textbox. In Fact I have 14(TextBox1, TextBox2, ...), this is my code so far:
Dim s As Integer = 0
While s > 14
s += 1
Dim txtBox As String = "TextBox" & CStr(s)
CObj(txtBox).Visible = False
End While
If txtBoxHowmany.Text = "" Then
Else
Dim s As Integer = 0
While s > txtBoxHowmany.Text
s += 1
Dim txtBox As String = "TextBox" & CStr(s)
CObj(txtBox).Visible = True
End While
End If
I created a list of text boxes and filled it in form Load. You can use this list in any method in your form.
In the Button.Click I used .TryParse to check the contents of TextBox7. I added a number range to the test with AndAlso's. AndAlso short circuits the If so that the following conditions will not be checked if the previous condition is False.
Next we use the .Take extension Function to get the text boxes we want to alter. A For Each loop actual changes the .Visible state.
Private TBoxes As New List(Of TextBox)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TBoxes.AddRange({TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6})
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim NumVisible As Integer
If Integer.TryParse(TextBox7.Text, NumVisible) AndAlso NumVisible > 0 AndAlso NumVisible < 15 Then
Dim VisibleBoxes = TBoxes.Take(NumVisible)
For Each tb In VisibleBoxes
tb.Visible = True
Next
Else
MessageBox.Show("Please enter a valid number.")
End If
End Sub
Design tip: use a spinner instead of a textbox.
Then you define the Minimum and Maximum values, while Value represents the currently-selected value. That makes the code more robust against incorrect input.
So the code could look like this:
dim s as integer = Me.spinner.Value
For i as Integer = 1 to s
Me.Controls("TextBox" & s.ToString).Visible = True
next
If value 5 is selected, then TextBox1 through TextBox5 become visible and you can continue with the rest and hide them as required.
Or a slightly more advanced example:
dim s as integer = me.spinner.Value
For Each ctl As Control In Me.Controls
Dim i as integer = 1
If TypeOf ctl Is TextBox Then
If ctl.Name.StartsWith("TextBox") Then
If ctl.Name = ("TextBox" & i.ToString()) ' eg TextBox1, TextBox5...
If i <= s Then ' counter <= value of spinner
ctl.Visible= True
Else
ctl.Visible= False
End If
End If
i += 1
End If
End If
Next
Here we loop on the form's child controls, look for those of Textbox type. i is an internal counter that is incremented at each occurrence of a TextBox control which name starts with 'TextBox'. If the control name starts with TextBox, and the rest of the string is a number <= spinner value, we set the Visible property to True. Otherwise, Visible is set to False.
So if the spinner value is 5, controls TextBox1 through TextBox5 should become visible, while the rest are to be hidden. The advantage to this approach is that the number of textboxes can be variable.
Disclaimer: untested code.
Update 09 March 2020
Here is a revised version that relies on a LINQ query to fetch a sorted list of textboxes in the form, assuming your controls are always named in the same pattern ie textbox1 through 14.
In theory this code could do the trick but it will not sort like I want ie textbox1 will be followed by textbox11, 12, 13, 14 and then textbox2.
Dim textboxes= From txt In Me.TableLayoutPanel1.Controls.OfType(Of TextBox)() _
Where txt.Name.StartsWith("TextBox") _
Order By txt.Name ' 1, 2, 14...
So I have tweaked the expression a little bit. I am assigning a variable textbox_number from LINQ to extract the number of the textbox:
Dim textboxes = From txt In Me.TableLayoutPanel1.Controls.OfType(Of TextBox)() _
Let textbox_number = Convert.ToInt32(txt.Name.Substring(7, txt.Name.Length - 7)) _
Where txt.Name.StartsWith("TextBox") _
Order By textbox_number ' 1, 2, 14...
This function is for demonstration purposes and should be improved to be made safer. It will work for your purpose though. By doing this trick I can perform a numeric sort so that that the controls are listed in the right order.
So if you select 5 in the spinner then controls 1 through 5 are made visible and the rest are hidden.
I have attached a screenshot. Note that I put all the textboxes in a TableLayoutPanel to improve presentation.
Probably, your controls are placed directly in the form and not in a container, then simply replace Me.TableLayoutPanel1.Controls with Me.Controls.
Public Class frmtextboxes
Private Sub butShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butShow.Click
Dim s As Integer = Me.spinner.Value ' number of textboxes to show
' LINQ query: get list of textboxes sorted by number
Dim textboxes = From txt In Me.TableLayoutPanel1.Controls.OfType(Of TextBox)() _
Let textbox_number = Convert.ToInt32(txt.Name.Substring(7, txt.Name.Length - 7)) _
Where txt.Name.StartsWith("TextBox") _
Order By textbox_number ' 1, 2, 14...
For Each ctl In textboxes
Console.WriteLine("TextBox found, name: " & ctl.txt.Name & "=> " & ctl.textbox_number)
If ctl.textbox_number <= s Then
Me.TableLayoutPanel1.Controls(ctl.txt.Name).Visible = True ' make control visible
Else
Me.TableLayoutPanel1.Controls(ctl.txt.Name).Visible = False ' hide control
End If
Next
End Sub
End Class

How can I essentially stop my VB program until a valid value is entered via Text Box?

How can I work around an invalid/null value entered into a text box?
Basically I have a simple program I need to develop to solve a simple quadratic equation:
Public Class Main
Private Sub btnHelp_Click(sender As System.Object, e As System.EventArgs) Handles btnHelp.Click
UserGD.Show()
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtStepX.Text = ""
lstResult.Items.Clear()
End Sub
Private Sub cmdGo_Click(sender As System.Object, e As System.EventArgs) Handles cmdGo.Click
Do
txtStepX.Text = InputBox("Please enter a valid value for x!", "Oops!", "")
Loop While String.IsNullOrEmpty(txtStepX.Text)
Dim stepx As Single
Dim X As Single
Dim y As Single
stepx = txtStepX.Text
Dim result As String
For X = -5 To 5 Step stepx
y = (3 * (X) ^ 2) + 4
result = ("x = " & X & " >>>>>>>>>> y = " & y)
lstResult.Items.Add(result)
Next
End Sub
End Class
This is the part I want to focus on:
Do
txtStepX.Text = InputBox("Please enter a valid value for x!", "Oops!", "")
Loop While String.IsNullOrEmpty(txtStepX.Text)
Dim stepx As Single
Dim X As Single
Dim y As Single
stepx = txtStepX.Text
Dim result As String
The above manages to check the text box (after its text value is changed by the Input Box) and loops fine, as long as it is empty... However, say I put a letter in, say, "l", it crashes and Visual Studio gives me the error "Conversion from string 'l' to type 'Single' is not valid." - which is fair enough. Although, I assumed the Null in isNullorEmpty meant it would catch invalid values, such as strings when it's supposed to be single.
I've tried quite a few things, and even my Computing teacher has been trying to get a solution.
I can't remember most of the things I've tried thus far so if I'll give whatever you guys come up with a go just to be on the safe side!
Update
Although not the clearest of code - here is what I found works the best for my needs:
'Written by a very tired and frustrated Conner Whiteside
'With his own blood.
'And sweat.
'And tears.
'Lots of tears.
'28/10/2014
Public Class Main
Private Sub btnHelp_Click(sender As System.Object, e As System.EventArgs) Handles btnHelp.Click
UserGD.Show()
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtStepX.Text = ""
lstResult.Items.Clear()
End Sub
' On Go button click
Private Sub cmdGo_Click(sender As System.Object, e As System.EventArgs) Handles cmdGo.Click
'Checks if Text Box value is a number
If IsNumeric(txtStepX.Text) Then
'Declares variables if Text Box value is in fact a number
Dim result As String
Dim stepx As Double
Dim X As Double
Dim y As Double
'Displays error message with a re-input opportunity if previously entered number is out of range.
Do While txtStepX.Text <= 0 Or txtStepX.Text > 10
'InputBox simply changed the value of the TextBox's Text. MUST be an InputBox or there will be nothing to break the loop.
txtStepX.Text = InputBox("The step size for the x values must not be a negative number or above 10." & vbCrLf & "Please enter another number for the step size of the x values.", "Oops!")
'Covers an Empty input given that IsNumeric does not. This can also prevent crashing if the 'Cancel' or 'X' is pressed on InputBox.
If txtStepX.Text = "" Then
'Exits Sub Class in order to avoid running mathematical operations (below) with a string "". Effectively allows a 'reset'.
Exit Sub
End If
Loop
'After all checks, sets Text Boxvalue to variable stepx
stepx = txtStepX.Text
'Loops the solving of the equation from x = -5 to x = 5 with the specified step size.
For X = -5 To 5 Step stepx
'sets the answer of the equation (y) to variable y.
y = (3 * (X) ^ 2) + 4
'concatenates a string in the required format.
result = ("x = " & X & " >>>>>>>>>> y = " & y)
'Adds the result to the List Box before repeating the process for the next value of x.
lstResult.Items.Add(result)
Next
'Catches any non numeric inputs in the Text Box or the Input Box e.g "l".
ElseIf Not IsNumeric(txtStepX.Text) Then
'Displays error message before ending If statement and Sub Class, allowing the user to return to the start and try another input. - No Input Box or Exit Sub needed.
MsgBox("Please enter a valid number for the step size of the values of x.", 64, "Oops!")
End If
End Sub
End Class
Honestly wouldn't have gotten anywhere if it weren't for your efforts!
I would simply check if the input is numeric.
If IsNumeric(txtStepX.text) then
// Your statements
Else
// MsgBox("Please enter a number")
End if
However, it will accept something like 3.5.4
A more complicated solution would be to limit the characters from being entered by checking on each keypress,
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar <> ChrW(Keys.Back) Then
If Char.IsNumber(e.KeyChar) Then
//Statements here
Else
e.Handled = True
End If
End If
End Sub
First, I recommend that you use the Double type instead of Single - it won't make any difference to how fast your program runs, but it will reduce rounding errors a lot.
Second, you can use Double.TryParse to check if a string can be parsed as a Double value. IsNumeric has some quirks which you do not want to find out about.
I took the liberty of adjusting the text which is shown to the user, as an "Oops!" before they have even tried to enter a value might be confusing, and it is better to tell them a number is needed than "a valid value":
Dim stepx As Double
Dim inp As String = ""
Dim inputTitle As String = "Number required"
Do
inp = InputBox("Please enter a number for x:", inputTitle)
' change the input box title to indicate something is wrong - if it is shown again.
inputTitle = "Oops!"
Loop While Not Double.TryParse(inp, stepx)
txtStepX.Text = stepx.ToString()

VB.Net get text after keypress

I am running some custom validations on textbox keypress event.
When a user presses a key I want to find out the text that would exist after that particular key press.
Eg. If the textbox currently contains 12.4 and the user press "6" key I want to find out what the text would be afterwards. I tried appending the e.KeyChar to the end of the textbox.text but there would be problems if the user highlights portions of the textbox and then press a key.
Is there anyway to detect the actual value that would exist after a key has been pressed?
You would have to disassemble the current text based on the current caret position, examine the incoming text, and then reassemble the text again:
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles TextBox1.KeyPress
Dim part1 As String = TextBox1.Text.Substring(0, TextBox1.SelectionStart)
Dim part2 As String = TextBox1.Text.Substring(TextBox1.SelectionStart + _
TextBox1.SelectionLength)
Dim character As String = String.Empty
If Char.IsDigit(e.KeyChar) Then
character = e.KeyChar.ToString
Dim result As String = part1 & character & part2
'Do something with result...
Else
e.Handled = True
End If
End Sub

keep track of richtext box text?

I'm new to the VB applications.My basic background is C.I just installed VB and learning stuff from google and microsoft help center. and I'm having fun with the things I'm doing but I got stucked up at one point and thats at richtext box.Is there any way to keep track of Rich textbox text in VB? So that I can append some text when user hits new line (i.e enter ) and do some task when he hits backspace. How do i keep track of richtextbox.?
I found
stringer = RichTextBox1.Lines(0) to read lines
& vbNewLine for new line
How do i read that user hit the new line character or backspace in vb rich textbox? because as far in C i used to do like these
if a = 13; \\ ascii for new line and 8 for backspace
I just want to do some task when user hits new line but I am unable to figure it out what the condition to be made.and Any good links for vb and documents on VB or on its windows application would be appreciated Too. Thank you in advance
You will want to link into the KeyDown event for the RichTextBox. Within this event you can modify the Text of the current line. Sample code for adding text to a line is:
Private Sub RichTextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles RichTextBox1.KeyDown
Dim textToAdd As String = " ** text to add **"
'Fire when the Enter key is pressed
If e.KeyCode = Keys.Enter Then
'Get the current cursor position
Dim cursorPos As Integer = RichTextBox1.SelectionStart
'Get the current line index
Dim index As Integer = RichTextBox1.GetLineFromCharIndex(cursorPos)
'Load all the lines into a string array
'This has to be done since editing via RichTextBox1.Lines(index) = "" doesn't always work
Dim lines() As String = RichTextBox1.Lines
'Add the text to the correct line
lines(index) &= textToAdd
'Assign the text back to the RichTextBox
RichTextBox1.Lines = lines
'Move the cursor to the correct position
RichTextBox1.SelectionStart = cursorPos + textToAdd.Length
End If
End Sub
All you need to do is check if the Enter or BackSpace key was pressed, like this:
Private Sub RichTextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles RichTextBox1.KeyDown
Select Case e.KeyCode
Case Keys.Enter
'Do stuff when Enter was pressed
Case Keys.Back
'Do stuff when BackSpace was pressed
End Select
End Sub
Note that Select Case is the same as the switch in C.

Text box validation

I am using many text boxes in a form.
How do i validate them,
In certain text boxes I have to use only text and in some I have to use only numbers.
Is using ASCII is a right method or is there any easier method to do this. If so please let me know the coding.
Above all other, don’t annoy the user. If I’m typing some text and the application prevents that (regardless of how it does that), I’m rightfully pissed off.
There are multiple values to handle this:
Use a NumericUpDown or a Slider control instead of a text box for numeric values (in other words: use the correct control instead of a general-purpose control).
Allow (more or less) arbitrary input and try to parse the user input in a meaningful way. For example, entering “+33 (0) 6 12-34-56” is an entirely meaningful format for a phone number in France. An application should allow that, and try to parse it correctly.
Granted, this is the hardest way, but it provides the best user experience.
Use the Validating event to validate input. This is automatically triggered whenever the user leaves the input control, i.e. when they have finished their input, and a validation will not annoy the user.
The MSDN documentation of the event gives an example of how this event is used correctly.
But do not use the KeyPress or TextChanged events to do validation. The first will disturb the users when entering text. The second will also annoy them when they try to paste text from somewhere else. Imagine the following: I am trying to copy an number from a website. Unfortunately, the text I have copied includes something else, too, e.g. “eggs: 14.33 EUR” instead of just “14.33”.
Now, the application must give me the chance to paste and correct the text. If I am not allowed to do that, the application is a UX failure. If the application uses the TextChanged event to prevent my pasting this text, I don’t get the chance to delete the offending text.
Text only limited to 40 characters:
<asp:RegularExpressionValidator ID="regexpText" runat="server"
ErrorMessage="Text only!"
ControlToValidate="txtName"
ValidationExpression="^[a-zA-Z]{1,40}$" />
Only Numbers:
<asp:RegularExpressionValidator ID="regexpNumber" runat="server"
ErrorMessage="Numbers only!"
ControlToValidate="txtName"
ValidationExpression="^[0-9]$" />
Wow, this can be a very broad topic...
For numeric textboxes, you should probably restrict input during KeyPress event:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
NOTE: This code sample is assuming WinForms, different approach must be used for web...
Regardless of the plat form, you should look into the validation controls offered by the framework, and that will allow you to validate that there is indeed input, values are in a specified range, and also using regex write more complicated validation rules.
The fastest way for validation is using regular expressions. They are harder to understand but offer better performance.
But you could do it also using string functions. Which is easier if you don't know regex but is less performant. This could be a viable option, depending on how hard the validation is.
Here and here are some posts that will help you with code samples.
Agreed that Regular Expressions might be faster, but ... well, here's how I've done it. Basically, this code is for a UserControl which contains a label, a text box, and an error provider. It also has various other properties, but here's the bit which deals with validation.
I do use this on the TextChanged event, because I don't want the user to continue typing if it's an invalid character; the rule checking "eats" the invalid character.
Public Enum CheckType
ctString = 0
ctReal = 1
ctDecimal = 2
ctInteger = 3
ctByte = 4
End Enum
Private mAllowNegative As Boolean = True
Private mAllowNull As Boolean = True
Private mCheckType As CheckType = CheckType.ctString
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
RuleCheckMe()
End Sub
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub RuleCheckMe()
'// Rule Checking
If Me.TextBox1.TextLength = 0 Then
If mAllowNull = False Then
Me.epMain.SetError(Me.TextBox1, "You are required to provide this value.")
Me.Valid = False
Else
Me.epMain.Clear()
Me.Valid = True
End If
Else
Select Case mCheckType
Case CheckType.ctString
If mInputMask.Length > 0 Then
'TODO: Figure out how to cope with input masks!
Me.Valid = True
Else
Me.Valid = True
End If
Case Else '// right now we're only testing for numbers...
If Not IsNumeric(Me.TextBox1.Text) And Me.TextBox1.Text <> "." And Me.TextBox1.Text <> "-" Then
If Not String.IsNullOrEmpty(Me.TextBox1.Text) Then
Me.TextBox1.Text = Me.TextBox1.Text.Remove(Me.TextBox1.Text.Length - 1, 1)
Me.TextBox1.SelectionStart = Me.TextBox1.Text.Length
End If
Me.epMain.SetError(Me.TextBox1, "This field does not accept non-numeric values.")
Me.Valid = False
ElseIf mAllowNegative = False And Me.TextBox1.Text.StartsWith("-") Then
Me.TextBox1.Text = Me.TextBox1.Text.Remove(Me.TextBox1.Text.Length - 1, 1)
Me.epMain.SetError(Me.TextBox1, "This field does not accept negative values.")
Me.Valid = False
ElseIf mCheckType = CheckType.ctByte And CType(Me.TextBox1.Text, Integer) > 255 Then
Me.epMain.SetError(Me.TextBox1, "This field does not accept values greater than 255.")
Me.Valid = False
Else
Me.epMain.Clear()
Me.Valid = True
End If
End Select
End If
End Sub
<System.ComponentModel.Browsable(True), _
System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible), _
System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always), _
System.ComponentModel.Category("Data")> _
Public Property AllowNegative() As Boolean
<System.Diagnostics.DebuggerStepThrough()> _
Get
Return mAllowNegative
End Get
<System.Diagnostics.DebuggerStepThrough()> _
Set(ByVal value As Boolean)
mAllowNegative = value
End Set
End Property
<System.ComponentModel.Browsable(True), _
System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible), _
System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always), _
System.ComponentModel.Category("Data")> _
Public Property AllowNull() As Boolean
<System.Diagnostics.DebuggerStepThrough()> _
Get
Return mAllowNull
End Get
<System.Diagnostics.DebuggerStepThrough()> _
Set(ByVal value As Boolean)
mAllowNull = value
End Set
End Property
<System.ComponentModel.Browsable(True), _
System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible), _
System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always), _
System.ComponentModel.Category("Data")> _
Public Property DataTypeCheck() As CheckType
<System.Diagnostics.DebuggerStepThrough()> _
Get
Return mCheckType
End Get
<System.Diagnostics.DebuggerStepThrough()> _
Set(ByVal value As CheckType)
mCheckType = value
End Set
End Property
i would like to share my text box validator..
Dim errProvider As New ErrorProvider
' Verify that this field is not blank.
Private Sub txtValidating(sender As Object,
e As System.ComponentModel.CancelEventArgs) Handles _
txtName.Validating, txtStreet.Validating, txtCity.Validating,
txtState.Validating, txtZip.Validating
' Convert sender into a TextBox.
Dim txt As TextBox = DirectCast(sender, TextBox)
' See if it’s blank.
If (txt.Text.Length > 0) Then
' It’s not blank. Clear any error.
errProvider.SetError(txt, “”)
Else
' It’s blank. Show an error.
errProvider.SetError(txt, “This field is required.”)
End If
End Sub
' See if any field is blank.
Private Sub Form1_FormClosing(sender As Object,
e As FormClosingEventArgs) Handles Me.FormClosing
If (txtName.Text.Length = 0) Then e.Cancel = True
If (txtStreet.Text.Length = 0) Then e.Cancel = True
If (txtCity.Text.Length = 0) Then e.Cancel = True
If (txtState.Text.Length = 0) Then e.Cancel = True
If (txtZip.Text.Length = 0) Then e.Cancel = True
End Sub
Private Sub TxtEmployeenumber_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtEmployeenumber.KeyPress
Dim c As Char
c = e.KeyChar
If Not (Char.IsDigit(c) Or c = "." Or Char.IsControl(c)) Then
e.Handled = True
MsgBox("numeric texts only")
End If
End Sub
just go to the keyup event of text box and enter the following code
100% it will work
if(Not Char.IsNumber(Chrw(e.Keycode))) Then
Messagebox.show ("only numeric values ")
textbox1.text=""
end if