How to create a class to check for keypress - vb.net

I have successfully created the code to check for keypress but my problem is,
I want it to be in a class so that I can reuse it in other forms as well.
How do I exactly do this?
Here is the code:
Private Sub money_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles money.KeyPress
Dim allowedChars As String = "0123456789" + vbBack
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
Lets say money is the name of the textbox.
I want to call this function as well in the other forms. How do I pass the variables needed, etc.

Change it into Public:
Public Sub money_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Dim allowedChars As String = "0123456789" + vbBack
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
In Form2:
Public Sub form2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles form2.KeyPress
Form1.money_KeyPress(sender, e)
End Sub

Related

when my barcode scanner scan a barcode my textbox1 will get System.Windows.Forms.TextBox, Text: error message. can someone help me

When my barcode scanner scans a barcode, in my textbox, I will get
System.Windows.Forms.TextBox, Text: error message.
I have tried many ways to solve the problem but still no success. Can someone pls help me take a look ? Thanks
Below is my code
Public Class Form1
Dim dataIn As String
'Dim userText As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort.PortName = "COM1"
SerialPort.BaudRate = CInt("9600")
SerialPort.Parity = Parity.None
SerialPort.StopBits = StopBits.One
SerialPort.Handshake = Handshake.None
SerialPort.Open()
SerialPort.ReadTimeout = 200
If SerialPort.IsOpen Then
' TextBox1.Text = ""
End If
End Sub
Private Sub SerialPort_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
dataIn = SerialPort.ReadExisting
dataIn = TextBox1.Text
TextBox1.Text += SerialPort.ReadExisting().ToString()
SetText(TextBox1.ToString())
End Sub
Delegate Sub SetTextCallback(ByVal text As String)
Private Sub SetText(ByVal text As String)
If Me.TextBox1.InvokeRequired Then
Dim d As SetTextCallback = New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {text})
Else
Me.TextBox1.Text = text.ToString
End If
End Sub
You can't set all those properties and use the methods without an instance of SerialPort.
I am not familiar with serial port code but I suspect that the sender in the DataReceived event is the serial port. So just Cast sender to SerialPort. Call the ReadExisting method which returns a string and assign it to the .Text property of the TextBox.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sp As New SerialPort()
sp.PortName = "COM1"
sp.BaudRate = CInt("9600")
sp.Parity = Parity.None
sp.StopBits = StopBits.One
sp.Handshake = Handshake.None
sp.Open()
sp.ReadTimeout = 200
End Sub
Private Sub SerialPort_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
TextBox1.Text += DirectCast(sender, SerialPort).ReadExisting
End Sub
Somewhere you need to dispose the port also.
With the Bar Code Scanners I have used, there's been no need to monitor the serial port as the drivers handle that. Normally the scanner simply reads and decoded the bar code and presents it as text to UI as if typed by the user. However, assuming you serial port code is correct, try this (this is a copy of code I've used that also works for setting Text on a Combobox too, so you'll need to delete that. I left it in in case it was helpful with other controls you might be using):
Private Sub SerialPort_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Dim ScannedText As String = DirectCast(sender, SerialPort).ReadExisting
SetText(TextBox1, ScannedText)
End Sub
Private Delegate Sub SetTextDelegate(ByVal obj As Object, NewText As String)
Private Sub SetTextSub(ByVal obj As Object, NewText As String)
Select Case obj.GetType.Name
Case "ComboBox"
CType(obj, ComboBox).Text = NewText
Case Else
CType(obj, TextBox).Text = NewText
End Select
End Sub
Private Sub SetText(ByVal obj As Object, NewText As String)
Dim del As SetTextDelegate
del = AddressOf SetTextSub
Dim parArray() As Object = {obj, NewText}
Select Case obj.GetType.Name
Case "ComboBox"
If CType(obj, ComboBox).InvokeRequired Then
CType(obj, ComboBox).Invoke(del, parArray)
Else
SetTextSub(obj, NewText)
End If
Case Else
If CType(obj, TextBox).InvokeRequired Then
CType(obj, TextBox).Invoke(del, parArray)
Else
SetTextSub(obj, NewText)
End If
End Select
End Sub

Replace string if followed by any character visual basic

I am new to Visual Basic. I want to use the like operator in a textbox to change a character if it is followed by any other character. But it should be on the key-up event.
Anyone please help me: how I can make the following code work?
Public Class Form1
Dim myString As String
Dim sMatch As Boolean = myString Like "x?"
Private Sub TextBox1_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
If sMatch = True Then
TextBox1.Text = TextBox1.Text.Replace(myString, "z")
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myString = "x"
End Sub
End Class
Try this and ask. Your variable myString was never getting it's value from the TextBox. You just set it to x in the load event.
Public Class Form1
Private Sub TextBox1_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
If TextBox1.Text Like "x?" Then
TextBox1.Text = TextBox1.Text.Replace(TextBox1.Text, "z")
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.Text = "x"
End Sub
End Class

textbox does not allow for backspace to be pressed?

I have made a textbox, which restricts character use to numbers and periods only. Nice, but now I can't enter backspace to amend any data typed in my textbox. How can I fix this?
Private Sub TextBox10_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox10.KeyPress
Dim allowedChars As String = "1234567890."
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
You can test for backspace by using
If e.KeyChar = ChrW(8) Then
MessageBox.Show("backspace!")
End If
So your whole code would become:
Private Sub TextBox10_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox10.KeyPress
Dim allowedChars As String = "1234567890."
If allowedChars.IndexOf(e.KeyChar) = -1 andalso
Not e.KeyChar = ChrW(8) Then
' Invalid Character
e.Handled = True
End If
End Sub
Similar question: How can I accept the backspace key in the keypress event?

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

Get InvalidOperatorException was unhandled upon compiling

Everything was compiling just fine until validation for text fields was implemented.
Why won't it compile?
An error occurred creating the form.
See Exception.InnerException for
details. The error is: External
component has thrown an exception.
The source:
Public Class frmAddStudent
Dim aryData(6) As String
Public Shared newStudentRecord As String
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Me.DialogResult = DialogResult.Cancel
End Sub
Private Sub btnAddStudent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddStudent.Click
'place all the student field data into the array of elements
aryData(0) = txtFirstName.Text
aryData(1) = txtLastName.Text
aryData(2) = txtMajor.Text
aryData(3) = txtPhone.Text
aryData(4) = txtEmail.Text
aryData(5) = txtGPA.Text
'join the array elements and place the result into a string variable
newStudentRecord = Join(aryData, " ")
'create a link between the form and the file with streamwriter and write to the text file
If System.IO.File.Exists(frmMain.FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(frmMain.FILE_NAME, True)
objWriter.WriteLine(newStudentRecord)
objWriter.Close()
End If
Me.DialogResult = DialogResult.OK
End Sub
Private Sub txtFirstName_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtFirstName.Validating
If txtFirstName.Text.Contains(" ") Or txtFirstName.Text.Length = 0 Or Not System.Text.RegularExpressions.Regex.IsMatch(txtFirstName.Text, "[a-z|A-Z]+$") Then
ErrorProvider1.SetError(txtFirstName, "First Name can't contain spaces or be of zero length and must consist of only letters")
e.Cancel = True
Else
ErrorProvider1.SetError(txtFirstName, "")
End If
End Sub
Private Sub frmAddStudent_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ErrorProvider1.BlinkStyle = ErrorBlinkStyle.NeverBlink
End Sub
Private Sub txtLastName_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtLastName.Validating
If txtLastName.Text.Contains(" ") Or txtLastName.Text.Length = 0 Or Not System.Text.RegularExpressions.Regex.IsMatch(txtLastName.Text, "[a-z|A-Z]+$") Then
ErrorProvider1.SetError(txtLastName, "Last Name can't contain spaces or be of zero length and must consist of only letters")
e.Cancel = True
Else
ErrorProvider1.SetError(txtLastName, "")
End If
End Sub
Private Sub txtMajor_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtMajor.Validating
If txtMajor.Text.Length > 0 Then
If Not System.Text.RegularExpressions.Regex.IsMatch(Strings.Left(txtMajor.Text, 1), "[a-z|A-Z]+$") Then
ErrorProvider1.SetError(txtMajor, "Major course code is incorrect")
Else
ErrorProvider1.SetError(txtMajor, "")
End If
Else
ErrorProvider1.SetError(txtMajor, "Major cant' be zero length")
End If
End Sub
End Class
EDIT: Here's also a link to a PrtSc of the problem: http://img88.imageshack.us/i/imageqc.gif/