help with my Bank form

skaryChinezeGuie

Well-known member
Joined
Apr 23, 2006
Messages
94
Programming Experience
Beginner
I got the deposit and the withdraw to work half right. It errors out when anything other than a number is entered though because it can't convert a string to an integer. How do i prevent anything other than numbers from being entered into the textboxes, including characters like "-" ? here's my code

Private
Sub BtnDeposit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDeposit.Click

Dim myMoney As Integer = Money
Dim myBank As Integer = Bank
Dim DepositAmount As Integer = TxtDeposit.Text

If DepositAmount <= myMoney Then
Bank = myBank + DepositAmount
Money = myMoney - DepositAmount
Call FrmBank_Load(Me, New System.EventArgs)
Else
MessageBox.Show("Try Again")
End If
End Sub

Private Sub BtnWithdraw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnWithdraw.Click

Dim myMoney2 As Integer = Money
Dim myBank2 As Integer = Bank
Dim WithdrawAmount As Integer = TxtWithdraw.Text

If WithdrawAmount <= myBank2 Then
Bank = myBank2 - WithdrawAmount
Money = myMoney2 + WithdrawAmount
Call FrmBank_Load(Me, New System.EventArgs)
Else
MessageBox.Show("Try Again")
End If
End Sub
:D
 
VB.NET:
if IsNumeric(TxtDeposit.Text) = False then
msgbox("Please enter a numberic value only!")
end if
 
it keeps erroring out on the Dim DepositAmount AsInteger = TxtDeposit.Text because it tries to convert anything but integers to integers. what can i do to fix this?
 
Last edited:
I would suggest that you download the WFC library in my signature and use their NumberBox control. It is a derived TextBox that accepts only numeric input and you can customise what type of input it accepts. If you want to use a standard TextBox then the the thing to do is to test whether the TextBox contains a number or not. Craig has already given you an example that will work, btu I'd recommend not using IsNumeric. The reason is that IsNumeric parses the string to determine whether it can be converted to a number. If it can then you have to parse the string again to get that number. The "proper" way to validate strings for numerical input is to use Double.TryParse:
VB.NET:
Dim value As Double
Dim number As Integer

If Double.TryParse(Me.TextBox1.Text, Globalization.NumberStyles.Integer, Nothing, value) Then
    'The parsed value is contained in the 'value' variable.
    number = CInt(value)
Else
    MessageBox.Show("Please enter and integer value.")
    Return
End If

MessageBox.Show("You entered the number " & number)
 
Note that it is also preferable to prevent the user entering invalid characters in the first place rather than telling them to fix it after the fact. You should always work under the tenet that prevention is better than cure. That's why the NumberBox is a good option, but you can implement similar validation yourself using the KeyPress event and various other things.
 
Back
Top