# Thread: Functions and validating

1. ## Functions and validating

I need some help with a homework assignment. I am supposed to create a few functions. one to calculate the charges for the number of days stayed at a hospital, another to calculate the charge for misc. charges, one to calculate the total charge, and a final one for validation. I'm not sure how close I am or how badly I have screwed the whole thing up, so if someone could help me out i would greatly appreciate it! oh and I do have to have option strict and option explicit on, if that matters.

vb.net Code:
```Private DaysHospitalized As Short = CDec(txtDays.Text) 'Holds days hospitalized
Private Meds As Decimal = CDec(txtMeds.Text) 'Holds Medication charges
Private Surgical As Decimal = CDec(txtSurgical.Text) 'Holds Surgery charges
Private Lab As Decimal = CDec(txtLab.Text) 'Holds Lab testing charges
Private Physical As Decimal = CDec(txtPhysical.Text) 'Holds Physical Therapy charges
Const COST_PER_DAY As Decimal = 350D 'Constant that holds the cost per day.
'Function to calculate the charges based on number of days stayed.
Function CalcStayCharges(ByRef DaysHospitalized As Short, ByRef COST_PER_DAY As Decimal) As Decimal
Dim StayCharges As Decimal = DaysHospitalized + COST_PER_DAY 'Holds the charges for days stayed.
'Return Result.
Return StayCharges
End Function
'Function to calculate all misc. charges
Function CalcMiscCharges(ByRef Meds As Decimal, ByRef Surgical As Decimal, ByRef Lab As Decimal, ByRef Physical As Decimal
) As Decimal
Dim MiscCharges As Decimal = Meds + Surgical + Lab + Physical 'Holds the sum of misc. charges
'Return Result.
Return MiscCharges
End Function
'Function to calculate the total charges.
Function CalcTotalCharges(ByRef StayCharges As Decimal, ByRef MiscCharges As Decimal) As Decimal
Dim TotalCharges As Decimal = StayCharges + MiscCharges 'Holds the sum of StayCharges and MiscCharges
'Return Result.
End Function

'=================================================frmHospitalInfo=====================================================================
Private Sub frmHospitalInfo_Load(sender As Object, e As EventArgs) Handles Me.Load
frmSplash.ShowDialog() 'Display Splash form when loading program.
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim TotalCharges As Decimal
TotalCharges = CalcTotalCharges()
lblTotalCost.Text = CalcTotalCharges()
End Sub
End Class```

2. ## Re: Functions and validating

Firstly, have you debugged your code, i.e. set a break point and stepped through the code?

3. ## Re: Functions and validating

No, I didn't know I needed to. I will try that. I have never done it before.

4. ## Re: Functions and validating

Ok so I put in a break point and tried to step through but my program is not updated based on the code. I originally did this program without creating any functions (because I read the directions poorely) so the whole thing worked perfectly, but now I deleted all that code and created my own functions, but I am getting errors. When I go to debug the program though it is working as if the old code is still in there. Is there a way to update it so I can debug correctly?

5. ## Re: Functions and validating

It sounds like you're running a build executable?, you run debug mode from the Designer. Set breakpoints then menu "Debug", "Start Debugging" or press "F5"

6. ## Re: Functions and validating

I think you are right. I tried a few things and then it started reading the current code instead of what I had deleted. I had to go but I will try debugging it when I get home. Hopefully that will help me find the problem.

7. ## Re: Functions and validating

It wont even let me Step into when trying to debug. I am getting two errors.
1. Error 1 Argument not specified for parameter 'MiscCharges' of 'Public Function CalcTotalCharges(ByRef StayCharges As Decimal, ByRef MiscCharges As Decimal) As Decimal'. C:\Users\Ethan\Documents\Visual Studio 2013\Projects\waHospitalCharges\waHospitalCharges\frmMain.vb 58 24 waHospitalCharges

and

2. Error 1 Argument not specified for parameter 'MiscCharges' of 'Public Function CalcTotalCharges(ByRef StayCharges As Decimal, ByRef MiscCharges As Decimal) As Decimal'. C:\Users\Ethan\Documents\Visual Studio 2013\Projects\waHospitalCharges\waHospitalCharges\frmMain.vb 58 24 waHospitalCharges

This seems to be related to where I am trying to set TotalCharges = CalcTotalCharges() but I don't understand enough about functions to understand what I am doing wrong. I have read through my text book, tried to copy what mine is compared to the books examples, and read on a few websites and through the help menu and can't figure this out. I just don't understand functions very well. If someone can explain it to me clearly it would be great.

vb.Net Code:
`Private DaysHospitalized As Short = CShort(txtDays.Text)    Private Meds As Decimal = CDec(txtMeds.Text) 'Holds Medication charges    Private Surgical As Decimal = CDec(txtSurgical.Text) 'Holds Surgery charges    Private Lab As Decimal = CDec(txtLab.Text) 'Holds Lab testing charges    Private Physical As Decimal = CDec(txtPhysical.Text) 'Holds Physical Therapy charges    Private Const COST_PER_DAY As Decimal = 350D 'Constant that holds the cost per day.    'Function to calculate the charges based on number of days stayed.    Function CalcStayCharges(ByRef DaysHospitalized As Short, ByRef COST_PER_DAY As Decimal) As Decimal         Dim StayCharges As Decimal = DaysHospitalized * COST_PER_DAY 'Holds the charges for days stayed.         'Return Result.        Return StayCharges     End Function    'Function to calculate all misc. charges    Function CalcMiscCharges(ByRef Meds As Decimal, ByRef Surgical As Decimal, ByRef Lab As Decimal, ByRef Physical As Decimal            ) As Decimal        Dim MiscCharges As Decimal = Meds + Surgical + Lab + Physical 'Holds the sum of misc. charges         'Return Result.        Return MiscCharges     End Function    'Function to calculate the total charges.    Function CalcTotalCharges(ByRef StayCharges As Decimal, ByRef MiscCharges As Decimal) As Decimal        Dim TotalCharges As Decimal = StayCharges + MiscCharges 'Holds the sum of StayCharges and MiscCharges         'Return Result.        Return TotalCharges     End Function    '===================================================btnCalculate======================================================================    Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click        Dim TotalCharges As Decimal         TotalCharges = CalcTotalCharges()        lblTotalCost.Text = TotalCharges.ToString     End Sub`

8. ## Re: Functions and validating

Those private variables declared at the beginning won't work. Those are form level variables, so the code you used (the CDec(whatever) statements) will execute before the constructor of the form runs. At that time, the controls on the form haven't been created, yet, so all those CDec calls will fail.

Another point is that you shouldn't be passing those arguments ByRef. By default, they will be passed ByVal, which is what you want. ByRef has its purposes, and this isn't one of them.

I applaud your desire to dive into coding, because I like that approach myself, but you would really benefit from some structured approach to this. This site is one that is often recommended here:

http://www.homeandlearn.co.uk/NET/vbNet.html

While it's a linnear tutorial, you can jump around.

9. ## Re: Functions and validating

So I got this to work. The program runs perfectly...except I can't make a Validate Function. I tried this:

Function ValidateInputFields() As Boolean
If Not Decimal.TryParse(txtDays, DaysHospitalized) And that is as far as I get because it won't accept DaysHospitalized. I'm not sure what it wants in there. I barely understand how to make a function and I don't know if I did them right, and I definitely don't know how to make a function with TryParse in it. can someone please help. Thank you!

vb.net Code:
`'Function to calculate the charges based on number of days stayed.    Function CalcStayCharges() As Decimal        Dim DaysHospitalized As Short = CShort(txtDays.Text) 'Holds the number of days stayed at the hospital.        Const COST_PER_DAY As Decimal = 350D 'Constant that holds the cost per day.        Dim StayCharges As Decimal 'Holds the total charge for days stayed         StayCharges = CDec(DaysHospitalized * COST_PER_DAY) 'Calculates the charge for days stayed.         'Return Result.        Return StayCharges     End Function     'Function to calculate all misc. charges    Function CalcMiscCharges() As Decimal        Dim Meds As Decimal = CDec(txtMeds.Text) 'Holds Medication charges        Dim Surgical As Decimal = CDec(txtSurgical.Text) 'Holds Surgery charges        Dim Lab As Decimal = CDec(txtLab.Text) 'Holds Lab testing charges        Dim Physical As Decimal = CDec(txtPhysical.Text) 'Holds Physical Therapy charges        Dim MiscCharges As Decimal         MiscCharges = Meds + Surgical + Lab + Physical 'Holds the sum of misc. charges         'Return Result.        Return MiscCharges     End Function    'Function to calculate the total charges.    Function CalcTotalCharges(ByRef StayCharges As Decimal, ByRef MiscCharges As Decimal) As Decimal        Dim TotalCharges As Decimal = StayCharges + MiscCharges 'Holds the sum of StayCharges and MiscCharges         'Return Result.        Return TotalCharges     End Function    '===================================================btnCalculate======================================================================    Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click              Dim TotalCharges As Decimal = CalcStayCharges() + CalcMiscCharges()         lblTotalCost.Text = TotalCharges.ToString     End Sub`

10. ## Re: Functions and validating

You declared DaysHospitalized as type Short, which is a short integer, yet you tried to parse it as a Decimal. That may not be the problem, though, because I don't see the function you mention, so the other problem could have to do with the scope of the variables. The only place I see DaysHospitalized is as a local variable in CalcStayCharges(), which would mean that the variable wasn't accessible anywhere else.

There are a couple general issues. I like the fact that you are converting strings to numbers, and you are using the right types in most cases. There's no good reason to use a Short...EVER. It's really just there for some legacy work. It may seem efficient to use a Short, since the number of days hospitalized had better not be higher than the size of a Short, but on modern computers (anything since the days of DOS, really), the Integer is the most efficient type, and your Short will probably be treated as an Integer, so you might as well just use an Integer and never use a Short.

You are correct to be using Decimals for the other things, though, as those look like money, and Decimal is the right type for that. However, CDec will crash if the text passed to it is either an empty string or has any character that isn't a number. Since you are talking about validating, and are correctly using Decimal.TryParse (except that you have to pass it a Decimal rather than a Short as the second argument), it seems like you've already figured that one out.

11. ## Re: Functions and validating

See I thought I needed my variables to be public to the whole class to make the validate function read them but when I put them as public under the class I get an error saying they are null??? And how can I make 1 validate function that will validate for all the inputs even if that one is a short (or integer)? Is there a way to make a function that can be used to validate all of the inputs? The one I was making will just work for one of the inputs I think, but I'm really supposed to have 1 function to validate all inputs...

12. ## Re: Functions and validating

If you want them available to the whole form, then they have to be declared outside of any method. They probably shouldn't be Public, because that would make them visible outside of the class itself, whereas you just say that you want them visible throughout the class, which sounds right to me. Therefore, you want to declare them Private outside of any method, as you had them in the snippet in post #7. What you did wrong in post #7 was that you didn't just declare them outside of the methods, you also set them to something. You can do that in some cases, but you can't set them to be a value from a control at that time, because the control doesn't even exist at that time, and even if the control did exist, it wouldn't have anything in it.

So what you need to do is declare the variable:

Private Meds As Decimal
etc.

but don't set them to anything at that time. In your validate method, you would just do something like this:
Code:
```If Decimal.TryParse(txtMeds.Text, Meds) Then
'It was a decimal, and Meds now holds it.
Else
'It wasn't a decimal, so scold the user.
End If```
The Validate method can have as many of those If blocks as you need for the variables. They'd all look about the same, except that one would be an integer rather than a decimal.

13. ## Re: Functions and validating

Ok this is what I have now. The validate function is working but something is wrong somewhere in my calculation functions because I am only getting 0 back as an output for Total Charges. I have checked everything and don't see any issues so I'm not sure what is going on.

vb.net Code:
`Public Class frmHospitalInfo     Private DaysHospitalized As Integer 'Holds the number of days stayed at the hospital.    Private Const COST_PER_DAY As Decimal = 350D 'Constant that holds the cost per day.    Private StayCharges As Decimal 'Holds the total charge for days stayed    Private Meds As Decimal 'Holds Medication charges    Private Surgical As Decimal 'Holds Surgery charges    Private Lab As Decimal 'Holds Lab testing charges    Private Physical As Decimal 'Holds Physical Therapy charges    Private MiscCharges As Decimal 'Holds total Misc Charges    Private TotalCharges As Decimal 'Holds the sum of StayCharges and MiscCharges     'Function to validate inputs.    Function ValidateInputFields() As Boolean        If CInt(txtDays.Text) < 0 Or txtDays.Text = String.Empty Then            MessageBox.Show("Please enter a positive numeric number for Days Stayed.")            txtDays.Clear()            Return False         End If         If CDec(txtMeds.Text) < 0 Or txtMeds.Text = String.Empty Then            MessageBox.Show("Please enter a positive numeric number for Medication cost.")            txtMeds.Clear()            Return False         End If         If CDec(txtSurgical.Text) < 0 Or txtSurgical.Text = String.Empty Then            MessageBox.Show("Please enter a positive numeric number for Surgery cost.")            txtSurgical.Clear()            Return False         End If         If CDec(txtLab.Text) < 0 Or txtLab.Text = String.Empty Then            MessageBox.Show("Please enter a positive numeric number for Lab cost.")            txtLab.Clear()            Return False         End If         If CDec(txtPhysical.Text) < 0 Or txtPhysical.Text = String.Empty Then            MessageBox.Show("Please enter a positive numeric number for Physical Therapy cost.")            txtPhysical.Clear()            Return False         End If        Return True    End Function     'Function to calculate the charges based on number of days stayed.    Function CalcStayCharges() As Decimal        DaysHospitalized = CInt(txtDays.Text) 'Sets DaysHospitalized to the corresponding text box.         StayCharges = CDec(DaysHospitalized * COST_PER_DAY) 'Calculates the charge for days stayed.         'Return Result.        Return StayCharges     End Function     'Function to calculate all misc. charges    Function CalcMiscCharges() As Decimal        Meds = CDec(txtMeds.Text) 'Sets Meds to the corresponding text box.        Surgical = CDec(txtSurgical.Text) 'Sets Surgical to the corresponding text box.        Lab = CDec(txtLab.Text) 'Sets Lab to the corresponding text box.        Physical = CDec(txtPhysical.Text) 'Sets Physical to the corresponding text box.          MiscCharges = Meds + Surgical + Lab + Physical 'Holds the sum of misc. charges         'Return Result.        Return MiscCharges     End Function    'Function to calculate the total charges.    Function CalcTotalCharges() As Decimal         TotalCharges = StayCharges + MiscCharges 'Holds the sum of StayCharges and MiscCharges         'Return Result.        Return TotalCharges     End Function    '===================================================btnCalculate======================================================================    Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click        If ValidateInputFields() Then             lblTotalCost.Text = TotalCharges.ToString        End If    End Sub`

14. ## Re: Functions and validating

You need to use Integer.TryParse and Decimal.TryParse. Using CInt or CDec will crash if the textbox is empty, regardless of the other part of the condition. The other part about TryParse is that it doesn't just check the number, it does the conversion, as well. In the example I showed, the first argument is the textbox, the second argument is the variable that will hold the value. So, if the conversion works, then Meds holds the correct value. The way you have it, you do the conversion with CDec or CInt, but you discard the result, so it never ends up in the variable in the validation method. You DO the conversion later on in CalcMiscCharges, but you never call it, so it never does anything. If you do the conversion in the Validate method, which you should, then there is no need to redo the conversion in CalcMiscCharges, but you do have to call CalcMiscCharges and CalcStayCharges at some time for them to be able to work. You'd also need to call CalcTotalCharges, so I would suggest that CalcTotalCharges should look like this:

Code:
```Function CalcTotalCharges() As Decimal
Return CalcMiscCharges() + CalcStayCharges()
End Function```

15. ## Re: Functions and validating

hmmm, I understand the issue with not calling functions. I fixed that issue and you were right it did fix the 0 I kept getting. I still don't understand why I need to use Decimal.TryParse though. The way I have it set up checks to make sure the input is not less then 0 or an empty string....which is what I need it to check. But the Decimal.TryParse and Integer.TryParse would just check to make sure that it can be converted to decimal or integer correct? Which still would leave the possibility of it being a negative number right? I really appreciate the help, the program is working as it should now, but I definitely would still like to really understand the TryParse issue, incase I need to use it later.

16. ## Re: Functions and validating

Have you gone away and read the documentation for tryparse? If the value is not a decimal your program will crash.

17. ## Re: Functions and validating

Yes I did but I didn't understand it exactly. I get it now, I played around with it and I get why it needs to be done like that. So I have that part covered and also I made it so it will not accept negative numbers. The last part of it I need it to be able to calculate even if a text box is left empty. I thought I could use an if statement that says for example If txtMeds.Text = String.Empty Then Meds = 0, that way the variable is initialized to 0 instead of just being empty. But that didn't work. How can I do this?

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

Click Here to Expand Forum to Full Width