Where do I put this code?

WackoWolf

Active member
Joined
Jan 6, 2006
Messages
39
Location
Rhode Island
Programming Experience
Beginner
I understand the code as to what it does, and I also understand why I want it. The problem I have is where do I put it. Do I put it in the button for the calculation or somewhere else? This is the code I want to use.

VB.NET:
Private Sub txt""_KeyPress (ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventsArgs) Handles txt"".KeyPress
Const Enter = Chr(13)
 
If e.KeyChar = ENTER Then
btnCalculate.Focus()
ElseIf Asc(e.KeyChar) < Asc("0") Or Asc(e.KeyChar) > Asc("9") Then e.Handled = True
Beep()
MessageBox>Show ("You can only enter a number here.", "Data Entry Error". MessageBoxButtons.Ok, MessageBoxIcon.Error)
 
End If
End Sub
 
what you have posted is the entire event for the button, just past it in the code window outside of any subs (the code you have is a sub)

although i would suggest a few changes to increase readability:
VB.NET:
Private Sub txt_KeyPress (ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventsArgs) Handles txt.KeyPress
  If Asc(e.KeyChar) = Keys.Enter Then
    btnCalculate.Focus()
  ElseIf IsNumeric(e.KeyChar) = False Then e.Handled = True
    Beep()
    MessageBox.Show("You can only enter a number here.", "Data Entry Error". MessageBoxButtons.Ok, MessageBoxIcon.Error)
  End If
End Sub
 
Depending on your policy regarding third-party controls, the Quantum WFC library contains a NumberBox control that handles all of the numerical validation for you. It is quite configurable and the library also includes many other great components. It is generally preferable to prevent a user making a mistake in the first place than fixing it after the fact. Prevention and cure, you know. :) See my signature for a link. Only supports .NET 1.x at the moment but a 2.0 version is on the way.
 
Back
Top