Validation of Decimal in text Box - vb.net

I am trying to validate wether a number is a decimal in Visual Basic. The results I get when the number is valid the msgBox shows. When it is not valid, I don't receive the msgBox and the program crashes with an error message that number has to be less than infinity.
I tried adding another If Not IsNumeric(txt1.text) then -- But received the same results.
Where did i go wrong?
If IsNumeric(txt1.text) Then
msgBox("good")
Else
msgBox("not good")
End If

Try using Double.TryParse or Decimal.TryParse instead of IsNumeric.
Dim result as Double = 0.0
if Double.TryParse(txt1.text, result) then
' valid entry
else
' invalid entry
end if

I have just had to write a function which restricts input to a text box to valid decimal values, and I came up with the following:
Private Sub validateDecimalTextBox(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) handles myTextBox.keyPress
Dim textBox As TextBox = DirectCast(sender, TextBox)
If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = "." And textBox.Text.IndexOf(".") < 0) Or (e.KeyChar = "-" And textBox.Text.Length = 0)) Then
e.Handled = True
End If
End Sub
This should restrict user input to decimal values, allowing negative values as well.
If you restrict the user inputs then when you get the value out from the text box you can be more confident that it is valid.
This solution is not complete however as it would allow a user to enter just "-" in the text box which would (presumably) not be a valid input for you. Therefore you can use the solutions that others have mentioned and use any of the following in a sensible way.
double.parse,
double.tryparse
isNumeric()
My personal preference would be for isNumeric() but the choice is really up to you.

You can ignore characters in the textbox's keypress event, like:
Private Sub txtValue_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress
If Not Char.IsDigit(e.KeyChar) Then
If Not (e.KeyChar = vbBack) Then
e.Handled = True
End If
End If
End Sub
not sure which version of VB you're using, assuming it's .NET

You can also use Textbox Keypress event. i.e
Private Sub Textbox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Textbox1.KeyPress
If (e.KeyChar < "0" Or e.KeyChar > "9") And e.KeyChar <> "." And e.KeyChar <> ControlChars.Back Then
e.Handled = True
Else
If e.KeyChar = "." Then
If Textbox1.Text.Contains(".") Then
Beep()
e.Handled = True
End If
End If
End If
End Sub
I hope this helps.

Related

textbox with numbers only but also pasting, copying, and selecting

I'm quite new in VB and got stuck on (i think) easy problem. I have a text box thats allows only numbers:
Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 49 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
from 1 to 9. But this box doesnt allows me to paste, copy, and select text...how can i change it? I know that KeyCode for Control is 17, and for 'V' is 86, but have no idea how to use it...
thanks for any help
The issue with KeyPress is that it calls only one KeyPress at a time. Hence multiple selections such as Ctrl+V, Ctrl+C would not work. Instead of flagging it under KeyPress, call the TextChanged. Add the below mentioned and the issue should be resolved. Copy, Paste and Selecting would now work as normal.
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
TextBox2.Text = System.Text.RegularExpressions.Regex.Replace(TextBox2.Text, "[^\d]", "") 'Removes all character except numbers
TextBox2.Select(TextBox2.Text.Length + 1, 1) 'To bring the textbox focus to the right
End Sub
If you necessarily want a TextBox you could combine the KeyDown and KeyPress events in order to block anything that isn't numbers while manually allowing Copy, Paste, Cut, etc.
Imports System.Text.RegularExpressions
Private Sub TextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox2.KeyPress
e.Handled = Char.IsNumber(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False 'Verify if input is a number or a control character (such as Backspace).
End Sub
Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
Dim TargetTextBox As TextBox = DirectCast(sender, TextBox)
e.SuppressKeyPress = True 'Start by blocking all key presses.
Select Case e.KeyData 'In order to not block some standard keyboard shortcuts.
Case Keys.Control Or Keys.C 'Copy
TargetTextBox.Copy()
Case Keys.Control Or Keys.X 'Cut
TargetTextBox.Cut()
Case Keys.Control Or Keys.V 'Paste
TargetTextBox.Paste()
TargetTextBox.Text = Regex.Replace(TextBox2.Text, "[^\d]", "")
Case Keys.Control Or Keys.A 'Select all.
TargetTextBox.SelectAll()
Case Else
e.SuppressKeyPress = False 'Allow all other key presses to be passed on to the KeyPress event.
End Select
End Sub
EDIT: Pardon the unintentional similar Regex, Arun Kumar.
This worked for me , write the below code on textbox keypress event
Try
If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) AndAlso (e.KeyChar <> Chr(22)) Then
MsgBox("Please enter numeric values", MsgBoxStyle.Information)
e.Handled = True
End If
Catch ex As Exception
pObj.WriteErrorLog(Me.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message, ex, True)
End Try

Show MessageBox message and ignore invalid characters in TextBox

I need the user to type only integer numbers in a TextBox. I already have that validation working, the problem is that I want to show a MessageBox to the user if he/she type a point, a letter, or the symbols !##. The MessageBox is shown to the user if an invalid character is typed but the letter still appears in the TextBox, which I don't want.
Could you please help me and tell me what's wrong with my code please
Private Sub txtCMS_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCMS.KeyPress
If (e.Handled = Not IsNumeric(e.KeyChar) And Not Char.IsControl(e.KeyChar)) = False Then
MessageBox.Show("Favor ingrese solo numeros", "Pablo Tobar says...", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
I use this code:
Private Sub txtCMS_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCMS.KeyPress
If Not (IsNumeric(e.KeyChar) OrElse Char.IsControl(e.KeyChar)) Then
e.Handled = True
MessageBox.Show("Por favor, ingrese sólo números", "Pablo Tobar says...", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Hope this can help you! Bye.
Your test for numeric input seems to have become mixed up with the code to ignore the invalid characters. You can use Char.IsDigit to check that the character is a decimal digit, and you need to set e.Handled = True to ignore the input.
Private Sub txtCMS_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtCMS.KeyPress
If Not Char.IsDigit(e.KeyChar) Then
MessageBox.Show("Invalid number")
e.Handled = True
End If
End Sub

Proper Textbox that only allow numeric and decimal in visual basic

I really need help in visual basic.
I have 3 textboxes that allow numeric and decimal with the code below:
If Not Char.IsDigit(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar)
AndAlso Not e.KeyChar = "." Then
e.Handled = True
End If
But I have encountered few problems:
I can put "." anywhere
when I try to add with each textbox, the result is a mess. example 1.2 + 3 =15
Can you fix my code so it can make a proper decimal calculation?
This can be helpful
Private Sub txtrate_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtmarks.KeyPress
If InStr(txtmarks.Text, ".") Then
e.Handled = Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar))
Else
e.Handled = Not ((Char.IsDigit(e.KeyChar) Or e.KeyChar = ".") Or Char.IsControl(e.KeyChar))
End If
End Sub

How to use the textbox1_keydown?

How do I use key_down event in my vb.net? I have seen so many codes on google but none of them working I don't understand where its going wrong
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx#Y600
http://www.daniweb.com/software-development/vbnet/threads/114278
http://forums.devshed.com/net-development-87/keypress-allow-only-letters-and-numbers-with-max-lenght-of-528176.html
http://social.msdn.microsoft.com/Forums/pl-PL/Vsexpressvb/thread/aab1d64c-a9dc-4dd2-8d2f-83a414e9c909
http://www.bigresource.com/VB-Lock-textbox-so-the-user-only-can-enter-numbers-a8mxDB7ouq.html
http://forums.devx.com/archive/index.php/t-96951.html
Above are the links I googled and they are many links =I have googled to work on key_down events on vb.net But my god its aint working I dont know what to do.
1) How do I use textbox1_keydown event are there any necessary steps taken before using it ( why its aint workin?)
2) can anyone post a sample of these "a textbox that allows only numbers from user using key_down"
3) I see people using e.keychar but in my vb.net(2008) I dont have that keyword I guess e.keycode must be used is that right? or e.keyvalue?
4) I see e.keycode = keys.A but I need to accept 'a' not "A" How do I specify a number or letter with their ascii value ?
Are you not able to use KeyPress for some reason?
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Char.IsDigit(e.KeyChar) Then
e.Handled = True 'Prevents all numbers from from being placed
End If
If Convert.ToInt32(e.KeyChar) = 97 Then
e.Handled = True 'Prevents "a" from being placed
End If
End Sub
This should do what you need. You can find a list of ASCII codes here if you don't have one already. Take a look at the intellisense for Char. and check out all the useful things you can filter on. You can also specify exact ASCII values by converting them to int.
It sounds like you are getting a little confused between KeyDown and KeyPress.
I think this is what you are looking for:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
If Not Char.IsNumber(e.KeyChar) Then
e.Handled = True
End If
End Sub
If you are trying to enter only numbers and the lower case "a" then:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
If Not (Convert.ToInt32(e.KeyChar) = Asc("a") Or Char.IsNumber(e.KeyChar)) Then
e.Handled = True
End If
End Sub

Only accept digits for textbox

I found this code for making my textbox only accept numbers.
Private Sub TextBox1_KeyPress(ByVal sender As System.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
But... the user can't delete the numbers using the backspace button. How do I do then?
Private Sub txtValue_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress
'Dim allowedChars As String = "0123456789"
'If allowedChars.IndexOf(e.KeyChar) = -1 Then
' ' Invalid Character
' e.Handled = True
'End If
'If (e.KeyChar = Microsoft.VisualBasic.Chr(8)) Then
' e.Handled = True
'End If
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If
End Sub
You also need to handle pasted text (there may not be a keypress). The best way to do this is with a MaskedTextBox.
voldemort
i develop your first code to allow the user to delete too.
Here is the code :
Dim BACKSPACE As Boolean
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Back Then
BACKSPACE = True
Else
BACKSPACE = False
End If
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If BACKSPACE = False Then
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
e.Handled = True
End If
End If
End Sub
I Hope My Code Was Useful To You :)
Use this code, it will help you
Public Function OnlyDigitsOnKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Try
If System.Char.IsDigit(e.KeyChar) = False And e.KeyChar <> Microsoft.VisualBasic.Chr(8) And e.KeyChar <> Microsoft.VisualBasic.Chr(46) Or (InStr(sender.text, ".") > 0 And e.KeyChar = Microsoft.VisualBasic.Chr(46))
Then
e.Handled = True
End If
Catch ex As Exception
Common.ErrorHandler(ex)
End Try
End Function
When I have had the requirement of an input which only accepts numbers, I have typically used the NumericUpDown class. It handles limits and decimals too.
Private Sub txtValue_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress
Dim allowedChars As String = "."
'If allowedChars.IndexOf(e.KeyChar) = -1 Then
' ' Invalid Character
' e.Handled = True
'End If
'If (e.KeyChar = Microsoft.VisualBasic.Chr(8)) Then
' e.Handled = True
'End If
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False And allowedChars.IndexOf(e.KeyChar) = -1 Then
e.Handled = True
End If
End Sub
Here is some code that I wrote. It allows the user to delete, and the user can make the textbox blank if they desire. It handles when the user types a disallowed character, and it also handles when the user pastes text into the textbox. If the user pastes a string into the box that is a mix of valid and invalid characters, the valid characters will appear in the textbox, and the invalid characters will not.
It also has logic in place to ensure that the cursor behaves normally. (A problem with setting the text to a new value is that the cursor is moved back to the beginning. This code tracks the original position, and makes adjustments to account for any invalid characters that are removed.)
This code can be placed in the TextChaned event of any textbox. Be sure to change the name from TextBox1 to match your textbox.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
Dim selStart As Integer = TextBox1.SelectionStart
Dim selMoveLeft As Integer = 0
Dim newStr As String = "" 'Build a new string by copying each valid character from the existing string. The new string starts as blank and valid characters are added 1 at a time.
For i As Integer = 0 To TextBox1.Text.Length - 1
If "0123456789".IndexOf(TextBox1.Text(i)) <> -1 Then 'Characters that are in the allowed set will be added to the new string.
newStr = newStr & TextBox1.Text(i)
ElseIf i < selStart Then 'Characters that are not valid are removed - if these characters are before the cursor, we need to move the cursor left to account for their removal.
selMoveLeft = selMoveLeft + 1
End If
Next
TextBox1.Text = newStr 'Place the new text into the textbox.
TextBox1.SelectionStart = selStart - selMoveLeft 'Move the cursor to the appropriate location.
End Sub
Note - if you have to do this for a bunch of textboxes, you can make a general purpose version of this by creating a sub that accepts a reference to a textbox as a parameter. Then you only need to call the sub from the TextChanged event.
Private Sub TMarksTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TMarksTextBox.KeyPress
If e.KeyChar < "0" OrElse e.KeyChar > "9" AndAlso e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub