Working with Forms and Controls in VB.NET KeyPress Event
The KeyPress event in VB.NET is an event that occurs when a key is pressed while the focus is on a control. This event is useful for handling input from the user, such as validation or formatting of input data.
Syntax
Private Sub control_KeyPress(sender As Object, e As KeyPressEventArgs) Handles control.KeyPress
' code
End Sub
Here, control
is the name of the control that the event is being handled for.
Example
Private Sub txtName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtName.KeyPress
If Not Char.IsLetter(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
End Sub
Output
The output of the above code will be that the KeyPress
event will handle the input of the txtName
control, allowing only letters and control keys to be entered.
Explanation
In the above example, we have a txtName
control that we want to validate to ensure that only letters are entered into the field. We handle the KeyPress
event for the control and check if the pressed key is a letter or a control key. If it is not, we set the e.Handled
property to True
, which prevents the key from being entered into the control.
Use
The KeyPress
event can be used to enforce input validation and formatting for controls in a VB.NET application. For example, you could use this event to ensure that a field only accepts numbers or dates in a specific format.
Important Points
- The
KeyPress
event in VB.NET allows you to handle input from the user while a control has focus. - You can use this event to enforce input validation and formatting for controls in a VB.NET application.
- The
e.KeyChar
property of theKeyPressEventArgs
object contains the character that was pressed. - The
e.Handled
property of theKeyPressEventArgs
object can be used to prevent the character from being entered into the control.
Summary
The KeyPress
event in VB.NET is a useful event for handling input from the user while a control has focus. It allows you to enforce input validation and formatting for controls in a VB.NET application, and provides access to the pressed key through the e.KeyChar
property of the KeyPressEventArgs
object.