You need to test the key before the text is changed and cancel/suppress if invalid.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim a As Double
a = TextBox1.Text
TextBox1.Text = Format(a, "#,###")
TextBox1.SelectionStart = Len(TextBox1.Text)
TextBox2.Text = TextBox1.Text
End Sub
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode < Keys.D0 Or e.KeyCode > Keys.D9 Then
e.SuppressKeyPress = True
End If
End Sub
Update: If you want to allow edit keys as well, here is an updated version of the KeyDown event.
Private validKeys() As Integer =
{
Keys.Delete,
Keys.Back,
Keys.Clear,
Keys.Home,
Keys.Left,
Keys.Right,
Keys.End,
Keys.D0,
Keys.D1,
Keys.D2,
Keys.D3,
Keys.D4,
Keys.D5,
Keys.D6,
Keys.D7,
Keys.D8,
Keys.D9
}
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
If Not validKeys.Contains(e.KeyCode) Then
e.SuppressKeyPress = True
End If
End Sub