vb.net Code:
Imports System.ComponentModel
Public Class Form1
Private Sub NumericTextBox_Validating(sender As Object, e As CancelEventArgs) Handles TextBox2.Validating,
TextBox1.Validating
Dim field = DirectCast(sender, TextBox)
If Not Double.TryParse(field.Text, Nothing) Then
field.SelectAll()
field.HideSelection = False
MessageBox.Show("Please enter a numeric value.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error)
field.HideSelection = False
'Don't let the user leave the field until they enter valid input.
e.Cancel = False
End If
End Sub
Private Sub saveButton_Click(sender As Object, e As EventArgs) Handles saveButton.Click
If Me.ValidateChildren() Then
'All fields have passed validation so save with confidence.
End If
End Sub
End Class
The Validating even is raised when the user tries to shift focus from the TextBox and setting e.Cancel prevents that from happening. Calling ValidateChildren will raise the event on all controls so even those that have never received focus will be validated.