This is my code as i want to validate my textbox using charracter not number so i m using keypress method
but i want to use it with get and set property using try catch block to pass the value from keypress event. But i am not able to do it
Public Class Form1
Property validatefirstname() As String
Get
Return TextBox1.Text
End Get
Set(ByVal value As String)
Try
If (value <> "") Then
TextBox1.Text = value
Else
MessageBox.Show("please input firstname")
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Set
End Property
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 90 And Asc(e.KeyChar) < 97 Or Asc(e.KeyChar) > 122 Then
e.Handled = True
MessageBox.Show("enter only alpha")
End If
End Sub
End Class
try with this one , It will work for you
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
If System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[^a-zA-Z\b]") Then
e.Handled = True
End If
End If
End Sub
Related
One particular cell in my datagridview will accept numeric only on edit mode.
What I want is if they leave the cell empty or 0 it will automatically change to value 1.
Here is my code below:
Private Sub dgvPrint_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles dgvPrint.EditingControlShowing
Dim txtEdit As TextBox = e.Control
RemoveHandler txtEdit.KeyPress, AddressOf CopiesText_KeyPress
AddHandler txtEdit.KeyPress, AddressOf CopiesText_KeyPress
End Sub
Private Sub CopiesText_KeyPress(sender As Object, e As KeyPressEventArgs) Handles CopiesText.KeyPress
If dgvPrint.CurrentCell.ColumnIndex = 5 Then
If IsNumeric(e.KeyChar.ToString()) Or e.KeyChar = ChrW(Keys.Back) Then
e.Handled = False
Else
e.Handled = True
MessageBox.Show("Invalid input." & vbCrLf & "Please enter numeric value.", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End If
End Sub
Thanks for your ideas guys. What I did is
Private Sub dgvPrint_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgvPrint.CellEndEdit
For X = 0 To dgvPrint.Rows.Count - 1
If Val(dgvPrint.Rows(X).Cells("dgvcCopies").Value) = 0 Then
dgvPrint.Rows(X).Cells("dgvcCopies").Value = 1
End If
Next
End Sub
It's working But I dont know if this is the right code to do.
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
I am using visual basic and I would like to know how to validate a textbox to accept 2 kinds of numbers (integers and decimal numbers)
just I know how to validate for integers:
Private Sub NumtelefonoTextBox_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles NumtelefonoTextBox.KeyDown
If Not ((e.KeyValue >= 48 And e.KeyValue <= 57) OrElse (e.KeyValue >= 96 And e.KeyValue <= 105) OrElse (e.KeyValue = 8)) Then
e.Handled = True
MsgBox("Este campo requiere únicamente valores númericos")
NumtelefonoTextBox.Text = vbNullChar
End If
End Sub
Abandon the Key events and check at event TextChanged if the number IsNummeric():
Private Sub txtBoxSample_TextChanged(sender As Object, e As EventArgs) Handles txtBoxSample.TextChanged
If Not IsNumeric(TxtBoxSample.Text) Then
MsgBox("Error!")
End If
End Sub
Use the text changed event handler
Private Sub NumtelefonoTextBox_TextChanged(sender As Object, e As EventArgs) Handles NumtelefonoTextBox.TextChanged
If Not Decimal.TryParse(NumtelefonoTextBox.Text, Nothing) Then
MessageBox.Show("Este campo requiere únicamente valores númericos")
End If
End Sub
Repected Sir,
I am restricting my textbox for numbers and decimal points only, i am able to get numbers and decimals only by the below function but not able to restrict making decimal points appearing twice on the input textbox. I guess If singleChars.IndexOf(KeyChar) > 0 And (Asc(KeyChar)) <> 8 has some errors and if its wrong how to solve it ?
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = myClasses.onlyCurrency(e.KeyChar)
End Sub
And my public function from class file is
Public Shared Function onlyCurrency(ByVal KeyChar As Char) As Boolean
Dim allowedChars As String
allowedChars = "0123456789."
Dim singleChars As String
singleChars = "."
If allowedChars.IndexOf(KeyChar) = -1 And (Asc(KeyChar)) <> 8 Then
Return True
End If
If singleChars.IndexOf(KeyChar) > 0 And (Asc(KeyChar)) <> 8 Then
Return True
End If
Return False
End Function
Yours faithfully
Murulimadhav
You are not paying attention to what has already been entered in your TextBox, therefore your function has no idea how many decimals points have been entered. You need to either pass the TextBox's Text into your function or prescreen it before sending to your function. Something like this:
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = myClasses.onlyCurrency(e.KeyChar, CType(sender, TextBox).Text)
End Sub
Public Shared Function onlyCurrency(ByVal KeyChar As Char, CurrentText As String) As Boolean
Dim allowedChars As String
allowedChars = "0123456789."
Dim singleChars As String
singleChars = "."
If KeyChar = singleChars Then
If CurrentText.Contains(singleChars) Then
Return True
End If
End If
If allowedChars.IndexOf(KeyChar) = -1 And (Asc(KeyChar)) <> 8 Then
Return True
End If
Return False
End Function
Try Like this
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Char.IsDigit(e.KeyChar) = False AndAlso e.KeyChar <> "." Then
e.Handled = True
ElseIf e.KeyChar = "." AndAlso TextBox1.Text.Trim.Contains(".") Then
e.Handled = True
Else
e.Handled = False
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