Show MessageBox message and ignore invalid characters in TextBox - vb.net

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

Related

Ignore enter keypress on dropdown with DropdownStyle=DropDownList

I've got a combobox, which the user can type into to filter out results.
To implement this, I've set the dropDownStyle to DropdownList and set the KeyUp event as follows
Private Sub cbRPP_KeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) Handles cbRPP.KeyUp
If boredUserProtection Then Return
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
e.Handled = True
Return 'Boss doesn't want enter to do anything
End If
ComboKeyPressed()
End Sub
Private Sub cbRPP_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cbRPP.SelectionChangeCommitted
If boredUserProtection Then Return 'boredUserProtection = a flag to prevent the user from typing into the box once they've entered some text
Try
boredUserProtection = True
menuButton.Select()
TooltipNotify("Loading")
cbRPP.Text = String.Empty
LoadRegion()
menuButton.Select()
Catch ex As Exception
ErrorReporter.Program.ReportError(ex, "RPPCalibator", "Handled Gracefully")
Finally
boredUserProtection = False
End Try
End Sub
The problem is that my boss has now asked me to prevent any action from occuring when he presses the enter key.
I've attempted to achieve this by intercepting the keypress and suppressing if enter, but it seems that this doesn't work when dropdownStyle=dropdownList
Private Sub cbRPP_KeyPress(sender As Object, e As KeyPressEventArgs) Handles cbRPP.KeyPress
If e.KeyChar = vbCrLf Then
e.Handled = True
Return 'Boss doesn't want enter to do anything
End If
End Sub
Private Sub cbRPP_KeyDown(sender As Object, e As KeyEventArgs) Handles cbRPP.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
e.Handled = True
Return 'Boss doesn't want enter to do anything
End If
End Sub
I'm just wondering if anyone can shed any light on how I can prevent any events happening on enter keyprss, as the one piece of advice I can readily find on Google (intercepting KeyDown or KeyUp) don't seem to work.
(I'm a pragmatist, so whatever form of solution you have would be much appreciated)

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

Editing existing key press event in visual basic

This is a small piece of code for a project I'm working on for my study.
We have to make a program in Visual Basic (with Visual Studio 2015) that copies text from the first text box and pastes it into the second one once you press the button that states: "Show Name".
We are meant to handle it so that if the value entered is between 'A' to 'Z' then it copies the text and pastes it normally once you press the button into the second text box.
We are also supposed to make it so that, if the value is a number (between 0 and 9) we are meant to have a message which pops up saying something like: "Error - You Entered a Number".
We are also supposed to make a box that pops up saying: "Error - You Entered Something Other Than a Number", if the value is a character other than a letter or a number. I am in kind of a rush and would appreciate any help soon.
Here is my code so far. (I know Keys.A and Keys.Z and the message box is wrong, which I need to fix, too):
Public Class MyFirstProgram
Private Sub DisplayTextButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisplayTextButton.Click
ShowTextBox.Text = EnterTextBox.Text
End Sub
Private Sub me_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
Dim letterEntered As Char
If e.KeyCode < Keys.A Or e.KeyCode > Keys.Z Then
MsgBox("Error - Use letter keys only!", MsgBoxStyle.OkOnly, )
Else
letterEntered = LCase(ChrW(e.KeyCode))
If ShowTextBox.Text = "" Then
ShowTextBox.Text = letterEntered
Else
ShowTextBox.Text = ShowTextBox.Text + letterEntered
End If
End If
End Sub
Private Sub ClearButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearButton.Click
EnterTextBox.Text = ""
End Sub
Private Sub MyFirstProgram_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.KeyPreview = True
End Sub
End Class
Oh, and I'm new to Visual Basic/programming; so, please try to be patient if you can. Sorry :/
Use KeyPress press event .. instead of keyDown
Private Sub me_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
'If e.KeyCode < Keys.A Or e.KeyCode > Keys.Z Then
' MsgBox("Error - Use letter keys only!", MsgBoxStyle.OkOnly, )
'Else
' Dim letterEntered = LCase(ChrW(e.KeyCode))
' ShowTextBox.Text = ShowTextBox.Text + letterEntered
'End If
'e.Handled = True
End Sub
Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
If Not Char.IsLetter(e.KeyChar) Then
MsgBox("Error - Use letter keys only!", MsgBoxStyle.OkOnly)
e.Handled = True
End If
End Sub
just look in to the IsNumeric Function if it could help you.

How to use ASCII code for Enter in vb.net

I am having a little problem getting my code to do what I want.
I want to prevent the user from using the Enter button when he/she is entering text into a text. The code I am using is:
Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Asc(e.KeyChar) = 13 Then
e.Handled = False
Else
e.Handled = True
MsgBox("Error.")
End If
End Sub
This not achieving my objective. Please how can I re-write this?
I agree with Tim3880. You are indeed keeping the user from entering anything with his/her keyboard; except the enter value. Your code is okay; only wrongly arranged, friend.
Try this:
Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Asc(e.KeyChar) = 13 Then
e.Handled = True
MsgBox("Error.")
Else
e.Handled = False
End If
End Sub

Validation of Decimal in text Box

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.