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
Related
I have a textbox and I am using the following to validate the user can only add numbers, but how can I let the user to write only one "."
Private Sub txtDiagnostic_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtConsultor.KeyPress
If e.KeyChar <> ChrW(Keys.Back) Then
If Char.IsNumber(e.KeyChar) Then
Else
e.Handled = True
End If
End If
End Sub
I was planing to use contains() or something but how can I realize the textbox has
only one dot? or how to allow the user can write a single dot and only one?
add this line before your first IF
If (e.KeyChar.ToString = ".") And (txtDiagnostic.Text.Contains(e.KeyChar.ToString)) Then
e.Handled = True
Exit Sub
End If
try this code good for money purposes
Private Sub LoanFeeTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles LoanFeeTextBox.KeyPress
If Char.IsControl(e.KeyChar) Then
ElseIf Char.IsDigit(e.KeyChar) OrElse e.KeyChar = "."c Then
If LoanFeeTextBox.TextLength = 12 And LoanFeeTextBox.Text.Contains(".") = False Then
LoanFeeTextBox.AppendText(".")
ElseIf e.KeyChar = "." And LoanFeeTextBox.Text.IndexOf(".") <> -1 Then
e.Handled = True
ElseIf Char.IsDigit(e.KeyChar) Then
If LoanFeeTextBox.Text.IndexOf(".") <> -1 Then
If LoanFeeTextBox.Text.Length >= LoanFeeTextBox.Text.IndexOf(".") + 3 Then
e.Handled = True
End If
End If
End If
Else
e.Handled = True
End If
End Sub
I'm creating a simple application in Vb.net where I need to perform certain validations. So I want a name textbox to accept only characters from a-z and A-Z for example.
For this I wrote the following code:
Private Sub txtname_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) > 65 Or Asc(e.KeyChar) < 90 Or Asc(e.KeyChar) > 96 Or Asc(e.KeyChar) < 122 Then
e.Handled = True
End If
End If
End Sub
But somehow it is not allowing me to enter characters. When I try to enter any character it does nothing.
What causes this problem and how can I resolve it?
Alternatively, you can do something like this,
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles txtName.KeyPress
If Not (Asc(e.KeyChar) = 8) Then
Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyz"
If Not allowedChars.Contains(e.KeyChar.ToString.ToLower) Then
e.KeyChar = ChrW(0)
e.Handled = True
End If
End If
End Sub
or if you still want the ASCII way, try this,
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtName.KeyPress
If Not (Asc(e.KeyChar) = 8) Then
If Not ((Asc(e.KeyChar) >= 97 And Asc(e.KeyChar) <= 122) Or (Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90)) Then
e.KeyChar = ChrW(0)
e.Handled = True
End If
End If
End Sub
both will behave the same.
This is a more abstract approach, but still effective nonetheless. It's straightforward and can just be added to the TextChanged event. You can use it with multiple textboxes by adding their handles to the sub and using a DirectCast().
Dim allowed As String = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
For Each c As Char In TextBox.Text
If allowed.Contains(c) = False Then
TextBox.Text = TextBox.Text.Remove(TextBox.SelectionStart - 1, 1)
TextBox.Select(TextBox.Text.Count, 0)
End If
Next
Summary: If an invalid character is entered, it will immediately be deleted (most of the time the character won't be visible long enough for the user to notice).
Private Sub txtname_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress
If AscW(e.KeyChar) > 64 And AscW(e.KeyChar) < 91 Or AscW(e.KeyChar) > 96 And AscW(e.KeyChar) < 123 Or AscW(e.KeyChar) = 8 Then
Else
e.KeyChar = Nothing
End If
End Sub
I hope this helps!
Am using below code to accept only letters, "-" or "'" when user is entering a person name (maybe it is simple and easier):
Private Sub txtEName1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtEName1.KeyPress
If Char.IsLetter(e.KeyChar) Or e.KeyChar = vbBack Or e.KeyChar = "-" Or e.KeyChar = "'" Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
I allowed the backspace in order to allow the user to remove letters in case of mistakes
Private Sub txtStudentName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtStudentName.KeyPress
If Not Char.IsLetter(e.KeyChar) And Not e.KeyChar = Chr(Keys.Delete) And Not e.KeyChar = Chr(Keys.Back) And Not e.KeyChar = Chr(Keys.Space) Then
e.Handled = True
End If
End Sub
i have the following code:
Private Sub TxtPStof_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtPStof.KeyPress
e.Handled = Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = ".")
End Sub
which allows only digits and . in my textbox, however i also need to be able to delete values using the backspace or the delete button.
Is this possible?
Thanks! :)
This is the wrong approach.
It’s universally agreed that restricting the user’s input is bad for the user experience, and you will invariably fail to handle special cases (what about Ctrl+V, for instance? Ah, you forgot about that. Everybody does).
Instead, .NET offers the Validating event for validating user input. You should intercept that event, not the keypress. Do allow users to enter text however they want; in particular, allow them to make mistakes (e.g. mistyping) without interruption – that would be extremely disruptive and not helpful.
Then, once they’re finished (because input focus leaves the control), do an input validation in one go.
While I totally agree with the answer from Konrad Rudolph
(It's really a messy affair to handle the user input in the KeyPress event)
I wish to give an answer at your question.
The MSDN in the KeyPress docs states that The KeyPress event is not raised by noncharacter keys. This means that you don't get the Delete key, but only the BackSpace key. You could handle this situation with this little change to your event handler
Private Sub TxtPStof_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtPStof.KeyPress
if e.KeyChar <> ControlChars.Back then
e.Handled = Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = ".")
end if
End Sub
If Char.IsLetterOrDigit(e.KeyChar) Or e.KeyChar = ControlChars.Back Or e.KeyChar = "." Then
e.Handled = False
Else
e.Handled = True
End If
this code works fine for me.
If Not ((Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57) Or Asc(e.KeyChar) = 46 Or Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 127) Then
e.KeyChar = ""
e.Handled = False
End If
try this one:
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
If Not (Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 46) Then e.Handled = True
End If
Private Sub textbox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textbox.KeyPress
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub
This should do what you want it to do.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim NumString = "0123456789.-"
If Not NumString.Contains(e.KeyChar) Then
If Asc(e.KeyChar) <> 8 Then 'BackSpace is allowed
e.KeyChar = ""
End If
Else
If e.KeyChar = "-" Then
If Len(Trim(TxtDcrAmt.Text)) > 0 Then
e.KeyChar = ""
End If
End If
If e.KeyChar = "." Then
If TxtDcrAmt.Text.Contains(".") Then
e.KeyChar = ""
End If
End If
If TxtDcrAmt.Text.Contains(".") Then
Dim TLen As Integer = 0
TLen = TxtDcrAmt.Text.IndexOf(".") + 2
If Len(Trim(TxtDcrAmt.Text)) > TLen Then
e.KeyChar = ""
End If
End If
End If
End Sub
Put this on keypress event. This allows dots and numbers only
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 46 Or Asc(e.KeyChar) > 57 Or (Asc(e.KeyChar) < 48 And Asc(e.KeyChar) > 46) Then
e.Handled = True
End If
End If
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
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.