locked
Question about code RRS feed

  • Question

  • I'm designing a program for a beginner VB college course and it's supposed to compile miles driven, gallons used and MPG for both a single leg  of a trip and for the entire trip.  When the button is pressed to calculate the MPG, the miles and gallons are put in their respective boxes below where a running tally is shown and the MPG is shown in it's own box for that single input.  A totals box is below that where, as the inputs are entered, shows a total mileage, gallons, and MPG usage for the entire trip.  The problem I am having is that the miles/gallons/mpgListBox.Items entry (used to compile the list in their respective boxes) is showing as an error in the VB 2010 Express Error List as " 'Items' is not a member of 'System.Windows.Forms.TextBox'.    I'm following the examples in the book and I'm still getting these errors.  Additionally, I'm getting another error for a text entry in the event that 0 is entered for gallons that is supposed to display "Gallons must be greater than zero."

    Here is the complete code that I have. 

    ' MPG Average

    Public Class MPGAverage
       ' The mpg average calculated individually and overall based on miles and fuel
       Private Sub calculateMPGButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles calculateMPGButton.Click

          ' User enters mileage
          If milesDrivenTextBox.Text <> String.Empty Then
             ' Add mileage to end of milesListBox
             milesListBox.Items.Add(milesDrivenTextBox.Text)
             milesDrivenTextBox.Clear()  ' Clears milesDrivenTextBox.Text
          End If

          ' User enters gas useage in gallons
          If gallonsUsedTextBox.Text <> String.Empty Then
             ' Add fuel used to end of gallonsListBox
             gallonsListBox.Items.Add(gallonsUsedTextBox.Text)
             gallonsUsedTextBox.Clear()  ' Clears gallonsUsedTextBox.Text
       Else gallonsUsedTextBox.Text = 0 Then gallonsListBox.Text = "Gallons must be greater than 0"

          End If

          Dim miles As Double ' Miles input
          Dim totalMiles As Double ' Total miles driven
          Dim fuel As Double ' Fuel input
          Dim totalFuel As Double ' Total fuel used
          Dim mpg As Double ' MPG calculation
          Dim totalMPG As Double ' Total MPG calculation

          ' Initialization
          miles = 0
          fuel = 0
          totalMiles = 0
          totalFuel = 0

          'Processing
          Do While totalMiles < milesListBox.Items.Count
             miles = milesListBox.Items(totalMiles) ' get next mileage input
             totalMiles += miles
          Loop

          Do While totalFuel < gallonsListBox.Items.Count
             fuel = gallonsListBox.Items(totalFuel) ' get next fuel input
             totalFuel += fuel
          Loop

          ' Termination
        If mpg <> 0 Then mpg = miles / fuel mpgListBox.Text ' Calculating mpg on single entries

          End If

          ' Displaying total miles, fuel and mpg
          totalResultsLabel.Text = "Total miles driven: " & totalMiles & vbCrLf & "Total gallons used: " & totalFuel & vbCrLf & "Total MPG: " & String.Format("{0:F}", totalMPG)

       End Sub

    End Class

     

    Thank for any help you can give on this.

    V/R,

    Brian

    Wednesday, December 15, 2010 10:23 PM

Answers

  • The first error you are getting indicates that you have added a textbox instead of a listbox when adding milesListBox to the form.

    Re the second problem:  an If statement can have the following elements

    If some condition Then
        DoSomething
    Elseif some other condition
        Do Something Else
    Else
        Something to do if neither of the above conditions is met
    End If

    The ElseIf and Else statements are optional but note that the Else cannot not specify a condition to be met.  You should be using an ElseIf

    Wednesday, December 15, 2010 10:46 PM
  • HI Brian,

     Your if statement is in the correct format but your logic is incorrect. There is two things wrong with the logic in this statement.

    1. You are testing the MPG for 0 and it will always be 0 since there is nothing in your application to change this value before making the test. Thus the if statement will never be true. Try using the ( miles <> 0 and CDbl( gallonsListbox.text) <> 0) in the if statement instead of MPG <> 0. This will test both numbers to make sure they are not zero before making the calculation.

    2. You are not converting the gallonsListBox.Text to a double so that it can be used in a calculation. Any listbox or textbox is a string even though it contains a number. Strings contain charectors that represent numbers and cannot be used in calculations without first being converted. 

    Hope this helps you

    Curtis


    Always Lost in Code, Always mark answers as correct if they answer you question and solve your problem. This way others when searching for similar problems can find the answer faster.
    Thursday, December 16, 2010 11:34 PM
  • Just to elaborate a little on "numerous other errors"

    Have a look at the code in your first loop:

    Do While totalMiles < milesListBox.Items.Count
         miles = milesListBox.Items(totalMiles)
         totalMiles += miles
    Loop

    What you are trying to do here is add together all the mileages you have added to the listbox.

    The test for the loop says "do this until the totalmiles is greater than the number of items in the listbox" which is not what you want.

    The first time round you set miles equal to the value of the first item in the listbox.

    You then add that value to totalmiles which will then almost certainly exceed the number of items in the box so the loop will only execute once. 

    What you should have here is something like:

    For Count as Integer = 0 to milesListBox.Items.Count - 1
        totalmiles += CDec(milesListBox.Items(Count))
    Next

    or you could use a For Each loop

    For Each Item as String in milesListBox.Items
        totalmiles += cdec(Item)
    Next

     

    Friday, December 17, 2010 12:15 AM
  • Why have you changed all your variables from Decimal to Integer. 

    Why didn't you take my advice to turn Option Strict On.

    VB is now doing implicit narrowing conversions for you which you are totally unaware of and which can give you wildly inaccurate results.

    Try entering 4.5 as the mileage and 1.5 as the fuel.  Obviously the correct result is 3 mpg but your code will tell you it is 2 mpg.  That is because VB is doing implicit conversions of the numbers you entered from Double to Integer.  As the conversion uses Bankers rounding the 4.5 gets rounded to 4 and the 1.5 gets rounded to 2.  If you had Option Strict On you would have seen this problem before running the program.

    I actually gave you the code for summing all the entries in the listbox:

        For Each Item As String In gallonsListBox.Items
            totalFuel += CDec(Item)
        Next

    So why did you change it to:

        For Each Item As String In gallonsListBox.Items
            totalFuel += CDec(fuel)
        Next


    There's little point offering advice if you are going to ignore it.

    Sunday, December 19, 2010 1:45 PM

All replies

  • The first error you are getting indicates that you have added a textbox instead of a listbox when adding milesListBox to the form.

    Re the second problem:  an If statement can have the following elements

    If some condition Then
        DoSomething
    Elseif some other condition
        Do Something Else
    Else
        Something to do if neither of the above conditions is met
    End If

    The ElseIf and Else statements are optional but note that the Else cannot not specify a condition to be met.  You should be using an ElseIf

    Wednesday, December 15, 2010 10:46 PM
  • Thank you Dave, I can't believe that overlooked something as simple as that but that took care of the majority of the problems.  I still don't see how this statement is incorrect though:

     

    If mpg <> 0 Then mpg = miles / fuel mpgListBox.Text ' Single entry MPG calculation
          End If

     

    The way I understand this is answer of miles / fuel will be placed in the mpgListBox as text for every entry of miles and gallons. 

     

    Would you, or anyone else be able to explain it a bit better? 

     

    Thanks

    Wednesday, December 15, 2010 11:17 PM
  • If you are putting the statement to be executed on the same line as the If condition Then you don't use the End If

    either

    If somecondition Then dosomething

    or

    If somecondition Then
        dosomething
    End If

     

    Wednesday, December 15, 2010 11:49 PM
  • Thanks Dave, it makes a lot more sense now.  Since I'm at work, I'll have to give this a try in the morning when I get off.  I appreciate all your help.

     

    Brian

    Thursday, December 16, 2010 1:11 AM
  • I was able to clear out all errors but now, when I enter in the miles and gallons used, it will populate in their respective single entry boxes, but no MPG.  Additionally, only the first entry will populate the bottom box which is supposed to display the total miles, gallons, and mpg.  I've researched the book and some online help forums and can't seem to figure out where I'm screwing up at.  Here is the completed code so far:

    ' MPG Average

    Public Class MPGAverage
       ' The mpg average calculated individually and overall based on miles and fuel
       Private Sub calculateMPGButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles calculateMPGButton.Click

          ' User enters mileage
          If milesDrivenTextBox.Text <> String.Empty Then
             ' Add mileage to end of milesListBox
             milesListBox.Items.Add(milesDrivenTextBox.Text)
             milesDrivenTextBox.Clear()  ' Clears milesDrivenTextBox.Text
          End If

          ' User enters gas useage in gallons
          If gallonsUsedTextBox.Text <> String.Empty Then
             ' Add fuel used to end of gallonsListBox
             gallonsListBox.Items.Add(gallonsUsedTextBox.Text)
             gallonsUsedTextBox.Clear()  ' Clears gallonsUsedTextBox.Text
          End If

          Dim miles As Decimal ' Miles input
          Dim totalMiles As Decimal ' Total miles driven
          Dim fuel As Decimal ' Fuel input
          Dim totalFuel As Decimal ' Total fuel used
          Dim mpg As Decimal ' MPG calculation
          Dim totalMPG As Decimal ' Total MPG calculation

          ' Initialization
          miles = 0
          fuel = 0
          totalMiles = 0
          totalFuel = 0

          'Processing
          Do While totalMiles < milesListBox.Items.Count
             miles = milesListBox.Items(totalMiles) ' get next mileage input
             totalMiles += miles
          Loop

          Do While totalFuel < gallonsListBox.Items.Count
             fuel = gallonsListBox.Items(totalFuel) ' get next fuel input
             totalFuel += fuel
          Loop

          ' Termination
          If mpg <> 0 Then mpg = miles / gallonsListBox.Text ' Single entry MPG calculation


          ' Displaying total miles, fuel and mpg
          totalResultsLabel.Text = "Total miles driven: " & totalMiles & vbCrLf & "Total gallons used: " & totalFuel & vbCrLf & "Total MPG: " & String.Format("{0:F}", totalMPG)

       End Sub
    End Class

     

    Thanks for any help you can give on this. 

    Brian

    Thursday, December 16, 2010 10:47 PM
  • Well you are displaying totalMPG but you have no code to calculate what it is so the display is correct.

    BTW - before you go any further you ought to turn Option Strict On and correct all the errors you then see.

    There are also numerous other errors in your code - did this really come from a book?

    Thursday, December 16, 2010 11:13 PM
  • HI Brian,

     Your if statement is in the correct format but your logic is incorrect. There is two things wrong with the logic in this statement.

    1. You are testing the MPG for 0 and it will always be 0 since there is nothing in your application to change this value before making the test. Thus the if statement will never be true. Try using the ( miles <> 0 and CDbl( gallonsListbox.text) <> 0) in the if statement instead of MPG <> 0. This will test both numbers to make sure they are not zero before making the calculation.

    2. You are not converting the gallonsListBox.Text to a double so that it can be used in a calculation. Any listbox or textbox is a string even though it contains a number. Strings contain charectors that represent numbers and cannot be used in calculations without first being converted. 

    Hope this helps you

    Curtis


    Always Lost in Code, Always mark answers as correct if they answer you question and solve your problem. This way others when searching for similar problems can find the answer faster.
    Thursday, December 16, 2010 11:34 PM
  • Just to elaborate a little on "numerous other errors"

    Have a look at the code in your first loop:

    Do While totalMiles < milesListBox.Items.Count
         miles = milesListBox.Items(totalMiles)
         totalMiles += miles
    Loop

    What you are trying to do here is add together all the mileages you have added to the listbox.

    The test for the loop says "do this until the totalmiles is greater than the number of items in the listbox" which is not what you want.

    The first time round you set miles equal to the value of the first item in the listbox.

    You then add that value to totalmiles which will then almost certainly exceed the number of items in the box so the loop will only execute once. 

    What you should have here is something like:

    For Count as Integer = 0 to milesListBox.Items.Count - 1
        totalmiles += CDec(milesListBox.Items(Count))
    Next

    or you could use a For Each loop

    For Each Item as String in milesListBox.Items
        totalmiles += cdec(Item)
    Next

     

    Friday, December 17, 2010 12:15 AM
  • Curtis and Dave,

    Since I'm at work right now I don't have access to VB (government computer) I will add the changes to the current code I have here and test it later this morning when I get off work.  I will be sure to post the results.  Thank you both for all your help, I sincerely appreciate it.

    Brian

    Friday, December 17, 2010 9:15 AM
  • Ok, I made some changes, and this is what I have.  It will now list all items (miles, gallons and MPG) in their respective boxes with the correct math for the MPG.  The bad part is that now in the bottom box where everything should be compiled together, the math that is being done is number of items * current entry for both totalMiles and totalFuel.  The MPG that shows is whatever the value is for the current entry.  I've looked all through the book I have for my class and the examples they show match up with what I have in the code.  Here is the code I currently have:

    ' MPG Average
    Public Class MPGAverage

       ' The mpg average calculated individually and overall based on miles and fuel
       Private Sub calculateMPGButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles calculateMPGButton.Click

          Dim miles As Integer ' Miles input
          Dim totalMiles As Integer ' Total miles driven
          Dim fuel As Integer ' Fuel input
          Dim totalFuel As Integer ' Total fuel used
          Dim mpg As Integer ' MPG calculation
          Dim totalMPG As Integer ' Total MPG calculation

          ' User enters mileage
          If milesDrivenTextBox.Text <> String.Empty Then
             ' Add mileage to end of milesListBox
             milesListBox.Items.Add(milesDrivenTextBox.Text)
             miles = milesDrivenTextBox.Text
             milesDrivenTextBox.Clear()  ' Clears milesDrivenTextBox.Text
          End If

          ' User enters gas useage in gallons
          If gallonsUsedTextBox.Text <> String.Empty Then
             ' Add fuel used to end of gallonsListBox
             gallonsListBox.Items.Add(gallonsUsedTextBox.Text)
             fuel = gallonsUsedTextBox.Text
             gallonsUsedTextBox.Clear()  ' Clears gallonsUsedTextBox.Text
          End If

          'Processing
          For Each Item As String In milesListBox.Items
             totalMiles += CDec(miles)
          Next

          For Each Item As String In gallonsListBox.Items
             totalFuel += CDec(fuel)
          Next

          ' calculate mpg and totalmpg
          mpg = miles / fuel
          totalMPG = totalMiles / totalFuel

          ' Displaying total miles, fuel and mpg
          mpgListBox.Items.Add(mpg) ' displays mpg in the listbox output

          totalResultsLabel.Text = "Total miles driven: " & totalMiles & vbCrLf & "Total gallons used: " & totalFuel & vbCrLf & "Total MPG: " & String.Format("{0:F}", totalMPG)
          ' Now that totalMPG is calculated above it will be output in your ResultsLabel.Text
       End Sub
    End Class

     

    Thanks for your help.

    Sunday, December 19, 2010 9:02 AM
  •  

      Private Sub calculateMPGButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles calculateMPGButton.Click
    
        Dim miles As Integer
        Dim totalMiles As Integer '<== Wrong
        Dim fuel As Integer
        Dim totalFuel As Integer '<== Wrong
        Dim mpg As Integer '<== Wrong
        Dim totalMPG As Integer '<== Wrong
    
        If milesDrivenTextBox.Text <> String.Empty Then
    
          milesListBox.Items.Add(milesDrivenTextBox.Text)
          miles = milesDrivenTextBox.Text '<== Wrong
          milesDrivenTextBox.Clear()
        End If
    
        If gallonsUsedTextBox.Text <> String.Empty Then
    
          gallonsListBox.Items.Add(gallonsUsedTextBox.Text)
          fuel = gallonsUsedTextBox.Text '<== Wrong
          gallonsUsedTextBox.Clear()
        End If
    
        For Each Item As String In milesListBox.Items
          totalMiles += CDec(miles) '<== Wrong
        Next
    
        For Each Item As String In gallonsListBox.Items
          totalFuel += CDec(fuel) '<== Wrong
        Next
    
        mpg = miles / fuel
        totalMPG = totalMiles / totalFuel
        mpgListBox.Items.Add(mpg)
        totalResultsLabel.Text = "Total miles driven: " & totalMiles & vbCrLf & "Total gallons used: " & totalFuel & vbCrLf & "Total MPG: " & String.Format("{0:F}", totalMPG)
    
      End Sub
    Sunday, December 19, 2010 1:23 PM
  • Why have you changed all your variables from Decimal to Integer. 

    Why didn't you take my advice to turn Option Strict On.

    VB is now doing implicit narrowing conversions for you which you are totally unaware of and which can give you wildly inaccurate results.

    Try entering 4.5 as the mileage and 1.5 as the fuel.  Obviously the correct result is 3 mpg but your code will tell you it is 2 mpg.  That is because VB is doing implicit conversions of the numbers you entered from Double to Integer.  As the conversion uses Bankers rounding the 4.5 gets rounded to 4 and the 1.5 gets rounded to 2.  If you had Option Strict On you would have seen this problem before running the program.

    I actually gave you the code for summing all the entries in the listbox:

        For Each Item As String In gallonsListBox.Items
            totalFuel += CDec(Item)
        Next

    So why did you change it to:

        For Each Item As String In gallonsListBox.Items
            totalFuel += CDec(fuel)
        Next


    There's little point offering advice if you are going to ignore it.

    Sunday, December 19, 2010 1:45 PM