Data Type validation in textbox - vb.net

Trying to make a validation where only letters can be entered into a textbox. I've got that part working, but I would also like the ability for the user to use the backspace button, and I'm not sure how
Private Sub TxtBoxCustForename_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtBoxCustForename.KeyPress
If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 122 Then 'Ensures only letters can be entered by using the ASCII converter'
e.Handled = True
MessageBox.Show("You may only input letters")
End If
End Sub

Input validation is a built-in feature of .NET. You don't need to capture key presses and manually code your own solution.
You might want to use a MaskedTextBox as suggested in this article:
https://learn.microsoft.com/en-us/dotnet/framework/winforms/user-input-validation-in-windows-forms

You can change your If statement like this:
If (Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 122) And Asc(e.KeyChar) <> 8 Then
Ascii 8 is the Backspace key.

Rather than using the KeyPress event, use the TextChanged event. Also, I would recommend using the IsNumeric function to test whether it is a number or not.
Private Sub TxtBoxCustForename_KeyPress(sender As Object, e As EventArgs) Handles TxtBoxCustForename.TextChanged
For Each entry as Char in TxtBoxCustForename.Text
If IsNumeric(entry) Then
MessageBox.Show("You may only input letters")
Exit For
End If
Next
End Sub

If you're going to use .NET then use .NET.
Private Sub TxtBoxCustForename_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtBoxCustForename.KeyPress
Dim keyChar = e.KeyChar
If Not Char.IsLetter(keyChar) AndAlso Not Char.IsControl(keyChar) Then
e.Handled = True
MessageBox.Show("You may only input letters")
End If
End Sub
This still doesn;t prevent the user pasting invalid text into the control though, so you still need to handle the Validating event or use a custom control that catches paste operations.

Related

phone number validation issue

I am trying to validate phone number textbox. I just want user to be able to enter only numeric values and only 10 digits in the textbox. I did it using keypress event.
it works fine but the problem is once the length of the input reaches to 10, it wont even allow the backspace.
Here is my code -
Private Sub tbphone_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tbphone.KeyPress
If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ChrW(Keys.Back)) Or tbphone.Text.Length >= 10 Then e.Handled = True
End Sub
Now, there can be a scenario where user enters all digits correctly but the last one. In that case he will not be able delete that last digit perhaps he will not be able to do anything in that textbox as the length of the input text is already 10 and now the e.handled is set to true.
Please suggest how can I achieve it...
Disclaimer: I have not touched vb.net in quite some time, say about a year. I am just providing a solution which I used previously and found it helpful.
You may refer to: This question has a similar issue and has been answered.
Regarding your 10 character limit, you can set the MaxLength property of the textbox either via the graphical editor or code.
You may refer to: How to set the textbox MaxLength property. (Please change the language to VB at the top of the page.)
I actually found the solution to my own question, I am putting it here so if anyone stuck validating textboxes with the same issue might get help.
I have set the e.handled to false if user presses BackSpace. And it worked...
Private Sub tbphone_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tbphone.KeyPress
If Not Char.IsDigit(CChar(CStr(e.KeyChar))) Or tbphone.Text.Length >= 10 Then e.Handled = True
If e.KeyChar = ChrW(Keys.Back) Then e.Handled = False
End Sub
i know it is already solved, but if i may add an answer.
If (e.KeyChar <= ChrW(47)) Or (e.KeyChar >= ChrW(58)) Then
If e.KeyChar = vbBack Then
Else
e.KeyChar = ChrW(0)
End If
Else
End If
i use this code in keypress event

How to force text being entered into a textbox into Uppercase?

I want to make the text that a user is typing into a textbox become uppercase. I know two ways to do this, which are:
Textbox1.Text = UCase(Textbox1.Text)
or
Textbox1.Text = Textbox1.Text.ToUpper
HOWEVER: both have the same problem (when embedded in a Textbox1_TextChanged event handler), which is that the cursor keeps being moved back to the start, so if you slowly type in, say abcdef, it comes out as FEDCBA. Is there a way to move the cursor back to the end of the string after each time it works to make the text uppercase?
go to textbox property, change CharacterCasing to Upper
Use the KeyPress event to detect lower case letters being entered, and convert them to uppercase as you go:
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii > 96 And KeyAscii < 123 Then
'Typed letter from "a-z", map it to "A-Z"
KeyAscii = KeyAscii - 32
End If
End Sub
Ucase() is used only after the person is done entering the text.
If you are using VB.NET then you just need to set the .CharacterCasing property of the TextBox to .Upper - No code needed. But if you wanted to use code for some reason, use this:
TextBox1.CharacterCasing = CharacterCasing.Upper
Why don't you just place the code Textbox1.Text = Textbox1.Text.ToUpper in the Textbox1_LostFocus event instead of the Textbox1_TextChanged event. It's so simple and it works even if you paste text into the field. As soon as your cursor moves to another field, the event is triggered, causing the text to change case from lower to upper.
You could also use:
Private Sub Textbox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Textbox1.KeyPress
e.KeyChar = UCase(e.KeyChar)
End Sub
... if you need to do some custom formatting or logic. Otherwise I'd also suggest using the default TextBox property CharacterCasing set to Upper.
Please note that this solution does not handle the situation when user is pasting text into the TextBox component and you have to programmatically take care of that situation too if needed, but the TextBox property CharacterCasing does it for you even if user is pasting text into the component.
Your version didn't quite work for me in Visual Basic 2019, but it formed the basis of this, which does (where "txtPrem1" is the TextBox):
Private Sub txtPrem1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtPrem1.KeyPress
Dim KeyAscii = AscW(e.KeyChar)
If KeyAscii > 96 And KeyAscii < 123 Then
'Typed letter from "a-z", map it to "A-Z"
KeyAscii = KeyAscii - 32
End If
e.KeyChar = ChrW(KeyAscii)
End Sub
How about this:
Private Sub MyText_TextChanged(sender As Object, e As EventArgs) _
Handles MyText.TextChanged
Dim oText As TextBox = CType(sender, TextBox)
oText.Text = oText.Text.ToUpper
oText.SelectionStart = oText.Text.Length
oText.SelectionLength = 0
End Sub

How can I make it so a TextBox will dynamically adjust the input as a currency format?

This app I'm designing has a TextBox named txtValue with the properties MaxLength set to 14 and TextAlign set to Right. I want txtValue to only accept currency, and dynamically format the input so the user doesn't need to add commas, only one period.
I managed to make it so txtValue will only accept numbers and one dot in the event txtValue_KeyPress.
txtValue_LostFocus will convert the input into currency format.
Here's my code so far:
Private Sub txtValue_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtValue.KeyPress
'Allows only one dot
If (e.KeyChar.ToString = ".") And (txtValue.Text.Contains(e.KeyChar.ToString)) Then
e.Handled = True
Exit Sub
End If
'Allows only 0 to 9 and dot (once)
If (e.KeyChar.ToString < "0" OrElse e.KeyChar.ToString > "9") _
AndAlso e.KeyChar <> ControlChars.Back _
AndAlso e.KeyChar.ToString <> "." Then
e.Handled = True
End If
End Sub
Private Sub txtValue_LostFocus(sender As Object, e As EventArgs) Handles txtValue.LostFocus
txtValue.Text = Format(Val(txtValue.Text), "000,000,000.00")
End Sub
I expect the input -q1w23456789012....34 to return the output 123,456,789,012.34, but the actual output after it loses focus is 123,456,789,012.30
This seems like an easy fix, like setting MaxLength to 15, but then if I don't type a period, it'll allow me to type 15 numbers and I only want up to 12 plus 2 after the period.
I expect the input -q1w234....5678 to return the output 1,234.56, but the actual output after it loses focus is 000,000,001,234.56
This seems like a more complex fix, because I don't want to use the LostFocus event to validate what I type. I want the KeyPress event to handle the input and dynamically format what I type.
In this case:
The input 1 would have the output 1.00
The input 123.4 would have the output 123.40
The input 1234.567 would have the output 1,234.56
All of this without needing the LostFocus event, but right now I'm using the LostFocus event because that's all my very limited knowledge allows me to do.
UPDATE
Alright I'm now using the Leave event, but then again I was only using LostFocus as a placeholder because in the end I want the TextBox to adjust what the user types as they type.
An alternative way to handle. For details on formating numbers for display try MS docs https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings or https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings
Private err As New ErrorProvider()
Private d As Decimal 'In case you want to use the value as a number somewhere else
Private Sub TextBox17_Validating(sender As Object, e As CancelEventArgs) Handles TextBox17.Validating
If Not Decimal.TryParse(TextBox17.Text, d) Then
e.Cancel = True
err.SetError(TextBox17, "This text box must contain a number.")
Else
err.Clear()
End If
End Sub
Private Sub TextBox17_Validated(sender As Object, e As EventArgs) Handles TextBox17.Validated
TextBox17.Text = d.ToString("C")
End Sub

Restriciton in combobox should not delete text in combox

Combobox should not accept any inputs and backspace. My code accepts backspace.
Private Sub ComboBox5_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox5.KeyPress
If Asc(e.KeyChar) <> 13 And Asc(e.KeyChar) <> 8 And Not IsNumeric(e.KeyChar) Or IsNumeric(e.KeyChar) Then
e.Handled = True
End If
End Sub
Your description and the code you posted don't match well. I am going to assume you left some words out, and you actually want to allow CR, BKSP, and any numeric. It looks like you want a numbers only ComboBox.
As Vincent said, your If statement is confusing. "Not IsNumeric(e.KeyChar) Or IsNumeric(e.KeyChar)" evaluates always as true, it's basically A or Not A.
For numbers only in ComboBoxes, I like this method, though there are lots of ways to skin that cat:
Private Sub ComboBox5_KeyPress(sender As Object, e As KeyPressEventArgs) Handles ComboBox5.KeyPress
Select Case AscW(e.KeyChar)
Case 13
'Do whatever you need with CR here
Case 8, 3, 22, 24, 26
'backsp copy paste cut undo
'let 'em be
Case Else
e.Handled = Not IsNumeric(e.KeyChar)
End Select
End Sub
If you really didn't want BackSpace, simply delete 8 from that case statement, or the whole case statement if you don't want the user to edit the text at all.
If you want to restrict your comboBox so that it should not accept inputs.
you can set the DropDownStyle property of your ComboBox to DropDownList
You can also set it programmatically
ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList

How to prevent special characters in datagridview using vb.net

I have a windows forms vb.net program that uses a datagridview. I'm trying to find a way to prevent a user from entering special characters (e.g. $,#,!,#,%,^,&) in my datagridview. When the user inputs a special character I have an approprioate message box appear explaining their mistake, then I provide them a default value. I have everything working except a way to prevent the special character or symbols. I'm thinking something like this has to work, but I can't seem to find any way of preventing this sort of entry:
If (columnindex = 0) Then 'checking value for column 1 only
Dim cellString = DataGridView1.Rows(rowindex).Cells(columnindex).value
If cellString String.IsSymbol(cellString) = true Then
MessageBox.Show("Special Characters Not Allowed")
End If
DataGridView1.Rows(rowindex).Cells(columnindex).value = "Default Value"
Exit Sub
End If
You can use the EditingControlShowing event to register a KeyPress function for the input box.
Private Sub YourDataGridView_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles YourDataGridView.EditingControlShowing
Try
RemoveHandler e.Control.KeyPress, AddressOf YourFunctionToPreventSpecialCharacters
Catch ex As Exception
End Try
If Me.dgvTableViewer.CurrentCell.ColumnIndex = YourDataGridView.Columns("YourColumn").Index Then
AddHandler e.Control.KeyPress, AddressOf YourFunctionToPreventSpecialCharacters
End If
End Sub
Try and Put this in the DataGridView's keydown event:
Private Sub DataGridView1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
Select Case e.KeyCode
Case Keys.D0 To Keys.D9 And e.Shift
MsgBox("NOPE.")
e.SuppressKeyPress = True
End Select
End Sub
That basically checks if the keypress is coming from the 0-9 keys on your computer and also if you are holding the SHIFT Key. If it is then it displays a Msgbox and Suppresses the keypress. This blocks chars on your keyboard's 0-9 shift !##$%^&*(). You can edit this like
Case Keys.A
e.Suppress ...
Msgbox ... etc