none
Unable to load .txt file into lst box

    Question

  • hi,

    Working on a problem for a book visual basic 2017. Does anything leap out at you why the the .txt file does not load?

    txt file:

    San Francisco4570New York City4310Boston3200Jersey City3200Washington D.C.3000Los Angeles2600San Jose2580Stamford2450Miami2400Seattle2210


    Code:

    Option Strict On

    Public Class frmApartmentRental
        'Class level variables.
        Public Shared _intSizeOfArray As Integer = 9
        Private _strCityName(_intSizeOfArray) As String
        Private _decRentAmount(_intSizeOfArray) As Decimal
        


        Private Sub frmApartmentRental_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim objReader As IO.StreamReader
            Dim strLocationAndNameOfFile As String = "C:\Users\Trevor Pan\source\repos\Apartment Rental By City\Apartment Rental By City\bin\Debug\rentals.txt"
            Dim intCount As Integer = 0
            Dim intFill As Integer
            Dim strFileError As String = "The file is not available. Restart when the file is available."

            'Verify the file exists.
            If IO.File.Exists(strLocationAndNameOfFile) Then
                objReader = IO.File.OpenText(strLocationAndNameOfFile)
                'Read the file line by line until the file is completed.
                Do While objReader.Peek <> -1
                    _strCityName(intCount) = objReader.ReadLine()
                    _decRentAmount(intCount) = Convert.ToDecimal(objReader.ReadLine())
                    intCount += 1

                Loop
                objReader.Close()

                'The ListBox object is filled with the City Names
                For intFill = 0 To (_strCityName.Length - 1)
                    lstCities.Items.Add(_strCityName(intFill))
                Next
            Else
                MsgBox(strFileError, , "Error")
                Close()
            End If
        End Sub

    End Class

    Saturday, December 02, 2017 9:09 PM

Answers

  • Recreate the data file manually using Notepad.

    Actually using WordPad would be better as you will be able to see the
    extra linefeeds and delete the blank lines that they cause.

    - Wayne

    • Marked as answer by trevorpan Thursday, December 07, 2017 8:48 PM
    Thursday, December 07, 2017 8:20 PM

All replies

  • Does anything leap out at you why the the .txt file does not load?

    The file format that is expected is

    San Francisco
    4570
    New York City
    4310
    Boston
    3200
    Jersey City
    3200

    etc.

    Saturday, December 02, 2017 9:14 PM
  • You know. I tried that. And still nothing. It's really strange. 

    Is there anything else? The book showed in a previous example the 

    Public Shared _intSizeOfArray As Integer = 9

    as 1 less than the number of items. So I tried 9, but also 10 (cities)

    Saturday, December 02, 2017 9:35 PM
  • You know. I tried that. And still nothing. It's really strange.

    Insert a breakpoint near the start and single step through the code one line at a time, examining the variables as you go.  Does each variable have the value you expect it to have at each step?  Does the code execute in the sequence that you expect it to execute?

    Saturday, December 02, 2017 9:51 PM
  • Hi Acamar,

    This is the first time I've used breakpoint. When you do this do you look for the where I've pointed to the arrow to debug? It seems like it should be counting, and if it's on 0 then it never initialized.

    Is that an accurate statement? If you can point to how you do this that would be helpful.

    Thank you


    • Edited by trevorpan Saturday, December 02, 2017 10:20 PM
    Saturday, December 02, 2017 10:20 PM
  • This is the first time I've used breakpoint. When you do this do you look for the where I've pointed to the arrow to debug? It seems like it should be counting, and if it's on 0 then it never initialized.

    It will be 0 for the first time through the loop, because you want the first item to be stored into the array at index 0.  It should increment for each pass through the loop.

    Saturday, December 02, 2017 10:26 PM
  • ok, you said go line by line, if I click the break point on the next line, what should a developer be looking for?

    Saturday, December 02, 2017 10:27 PM
  • ok, you said go line by line, if I click the break point on the next line, what should a developer be looking for?

    No need to set the breakpoint on the next line.  Just single step and it will stop at the next line (Debug \ Step Into or F11, depending on your version of VS).

    You would expect to see the array index increase as each loop iteration executes, and the text file lines should be listed in the array.

    Saturday, December 02, 2017 10:35 PM
  • Trevor,

    If this is schoolwork then you don't have an option here, but if you do have an option, you might consider using a different type of text file: XML.

    That would handle things quite nicely.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Saturday, December 02, 2017 11:07 PM
  • Trevor,

    If the data in your text file is as Acamar thinks (as shown below):

    San Francisco
    4570
    New York City
    4310
    Boston
    3200
    Jersey City
    3200
    Washington D.C.
    3000
    Los Angeles
    2600
    San Jose
    2580
    Stamford
    2450
    Miami
    2400
    Seattle
    2210

    The following is an idea that you might use. For your use you'll probably want to scope it higher than I have it but this is basic idea:

    Public Class Form1
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    
            Dim desktop As String = _
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    
            Dim textFilePath As String = _
                IO.Path.Combine(desktop, "Rentals.txt")
    
            Dim rentals() As RentalInfo = GetRentals(textFilePath)
    
            Stop
    
            ' Now hover your mouse over "rentals()" above
            ' and you'll see the data from the text file.
    
        End Sub
    
    
    
        Private Function GetRentals(ByVal filePath As String) As RentalInfo()
    
            Dim retVal() As RentalInfo = Nothing
    
            If Not String.IsNullOrWhiteSpace(filePath) Then
                Dim fi As New IO.FileInfo(filePath)
    
                If fi.Exists Then
                    Dim tempList As New List(Of RentalInfo)
                    Dim instance As RentalInfo = Nothing
    
                    Using rdr As New System.IO.StreamReader(fi.FullName)
                        Do While rdr.Peek() >= 0
                            Dim itm As String = rdr.ReadLine
    
                            If Integer.TryParse(itm, New Integer) Then
                                instance.RentalPrice = CDec(itm)
                                tempList.Add(instance)
                            Else
                                instance = New RentalInfo With {.Location = itm}
                            End If
                        Loop
                    End Using
    
                    retVal = tempList.ToArray
                End If
            End If
    
            Return retVal
    
        End Function
    
    
    
        Private Class RentalInfo
            Public Property Location As String
            Public Property RentalPrice As Decimal
    
            Public Overrides Function ToString() As String
                Return String.Format("{0} | {1:c0}", Location, RentalPrice)
            End Function
        End Class
    End Class

    Once you have it in a class like that, you have total control over using the data in the collection because of encapsulation.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, December 03, 2017 2:41 PM
  • Acamar, 

    I've tried out step into (f11). thank you.

    when the line 16 is stepped into, it shows  "nothing". (red arrow)

    Does this mean, it's not reading the file? 




    • Edited by trevorpan Sunday, December 03, 2017 4:18 PM
    Sunday, December 03, 2017 3:57 PM
  • Hi Frank,

    Definitely will use one in projects after this course, but this one deals with txt files..

    Sunday, December 03, 2017 3:58 PM
  • Hi Frank,

    Definitely will use one in projects after this course, but this one deals with txt files..

    Show the contents of the file then please?

    When you reply back, click the "<>" icon and set it for VB Net. Post the contents of the file in that and it'll be easier to read and copy from.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, December 03, 2017 4:03 PM
  • Frank,

    Just read your link on encapsulation. Thx.

    For this assignment the teacher specified the .txt file be in the Dubug folder as "rentals.txt" however, that throws the error popup. Which is why I included the entire path. Any ideas on why the file will not populate the lstCities?

    Sunday, December 03, 2017 5:04 PM
  • I'm not sure why the spaced lines are included. The file itself does not have spaced lines.

    San Francisco
    
    4570
    New York City
    4310
    Boston
    3200
    Jersey City
    3200
    Washington D.C.
    
    3000
    Los Angeles
    
    2600
    San Jose
    2580
    
    Stamford
    
    2450
    Miami
    
    2400
    Seattle
    
    2210
    
    



    • Edited by trevorpan Sunday, December 03, 2017 5:09 PM
    Sunday, December 03, 2017 5:06 PM
  • Frank,

    Just read your link on encapsulation. Thx.

    For this assignment the teacher specified the .txt file be in the Dubug folder as "rentals.txt" however, that throws the error popup. Which is why I included the entire path. Any ideas on why the file will not populate the lstCities?

    So long as you're not writing to it, then having it in the \bin\Debug directory should work.

    ***** EDIT *****

    This is homework. You'll have to find it yourself and to do that, use a breakpoint.

    Sunday, December 03, 2017 5:16 PM
  • _strCityName(intCount + 1) = objReader.ReadLine()

    Tried this out, the file does not read. 

    Also, created a new form "test". Should I name the list box tempList?

    Does not seem to pull the text file. In this case I put a copy on the desktop. (I believe that's where your code says to place it.)

    Sunday, December 03, 2017 6:32 PM
  • Trevor,

    For my example I'm using a file named "Rentals.txt" on my desktop. It you step into it you'll probably find that it's not finding that file in your example; change it accordingly.

    *****

    Back to yours though, it's reading each line even though there are 'sets' of data. I think that setting up a class is the best way to do since you can use encapsulation but a very old way would be to use two arrays (or generic lists) and rely on the index. So long as nothing changes the index (like sorting) that will work.

    I'm not suggesting that it's a great idea at all, but it's "one way you can do this".

    If you put a breakpoint in and step into it (your code) you'll see it oscillate: City name, then price, the city name, then price.

    That's not a great way to have data but that's what you have.

    Work through the logic. My suggestion is to to know that it's a number with .TryParse; but you can do it with a simple counter.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, December 03, 2017 6:39 PM
  • Trevor,

    I don't like this but it will work.

    Try it on your end and change the path to your own text file's path:

    Public Class Form1
        Private _cityNames As List(Of String)
        Private _apartmentPrices As List(Of Decimal)
    
    
    
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                       Handles MyBase.Load
    
            _cityNames = New List(Of String)
            _apartmentPrices = New List(Of Decimal)
    
            Dim desktop As String = _
                 Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    
            Dim textFilePath As String = _
                IO.Path.Combine(desktop, "Rentals.txt")
    
            GetRentals(textFilePath)
    
            Stop
    
        End Sub
    
    
    
        Private Sub _
            GetRentals(ByVal filePath As String)
    
            If Not String.IsNullOrWhiteSpace(filePath) Then
                Dim fi As New IO.FileInfo(filePath)
    
                If fi.Exists Then
                    Dim counter As Integer = 0
    
                    Using rdr As New System.IO.StreamReader(fi.FullName)
                        Do While rdr.Peek() >= 0
                            Dim itm As String = rdr.ReadLine
    
                            If counter Mod 2 = 0 Then
                                _cityNames.Add(itm)
                            Else
                                _apartmentPrices.Add(CDec(itm))
                            End If
    
                            counter += 1
                        Loop
                    End Using
                End If
            End If
    
        End Sub
    End Class
    


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, December 03, 2017 6:50 PM
  • Trevor,

    Just for a comparison, this is one of many reasons that using a class - even a simple one like I showed - is much better than two disparate collections:

    Public Class Form2
        Private Sub _
            Form1_Load(sender As System.Object, _
                       e As System.EventArgs) _
                   Handles MyBase.Load
    
            Dim desktop As String = _
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    
            Dim textFilePath As String = _
                IO.Path.Combine(desktop, "Rentals.txt")
    
            Dim rentals() As RentalInfo = GetRentals(textFilePath)
    
            ' You can't do the following using two separate
            ' collections; encapsulation is what allows the
            ' following to work:
    
            Dim minPrice As Decimal = _
                (From ri As RentalInfo In rentals _
                     Select ri.RentalPrice).Min
    
            Dim maxPrice As Decimal = _
                (From ri As RentalInfo In rentals _
                     Select ri.RentalPrice).Max
    
            Dim meanPrice As Decimal = _
                (From ri As RentalInfo In rentals _
                     Select ri.RentalPrice).Average
    
            Dim minCity = From ri As RentalInfo In rentals _
                              Where ri.RentalPrice = minPrice _
                                  Select ri.Location
    
            Dim maxCity = From ri As RentalInfo In rentals _
                              Where ri.RentalPrice = maxPrice _
                                  Select ri.Location
    
            If minCity IsNot Nothing AndAlso maxCity IsNot Nothing Then
                Dim sb As New System.Text.StringBuilder
    
                sb.AppendLine(String.Format("The lowest apartment price of {0:c0}", minPrice))
                sb.AppendLine(String.Format("is located in the city of {0}.", minCity.First))
                sb.AppendLine()
                sb.AppendLine(String.Format("The highest apartment price of {0:c0}", maxPrice))
                sb.AppendLine(String.Format("is located in the city {0}.", maxCity.First))
                sb.AppendLine()
                sb.AppendLine("The average apartment price in the selected")
                sb.AppendLine(String.Format("cities is {0:c0}.", meanPrice))
    
                MessageBox.Show(sb.ToString, "Results")
            End If
    
            Stop
    
        End Sub
    
    
    
        Private Function GetRentals(ByVal filePath As String) As RentalInfo()
    
            Dim retVal() As RentalInfo = Nothing
    
            If Not String.IsNullOrWhiteSpace(filePath) Then
                Dim fi As New IO.FileInfo(filePath)
    
                If fi.Exists Then
                    Dim tempList As New List(Of RentalInfo)
                    Dim instance As RentalInfo = Nothing
    
                    Using rdr As New System.IO.StreamReader(fi.FullName)
                        Do While rdr.Peek() >= 0
                            Dim itm As String = rdr.ReadLine
    
                            If Integer.TryParse(itm, New Integer) Then
                                instance.RentalPrice = CDec(itm)
                                tempList.Add(instance)
                            Else
                                instance = New RentalInfo With {.Location = itm}
                            End If
                        Loop
                    End Using
    
                    retVal = tempList.ToArray
                End If
            End If
    
            Return retVal
    
        End Function
    
    
    
        Private Class RentalInfo
            Public Property Location As String
            Public Property RentalPrice As Decimal
    
            Public Overrides Function ToString() As String
                Return String.Format("{0} | {1:c0}", Location, RentalPrice)
            End Function
        End Class
    End Class


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, December 03, 2017 7:46 PM
  • when the line 16 is stepped into, it shows  "nothing". (red arrow)

    Does this mean, it's not reading the file?

    No.  Objreader is a variable that will be used to refer to a Streamreader.   But the Streamreader it will refer to doesn't exist until line 23.   OpenText creates a Streamreader and returns it as a result of the function.  That return value is assigned to the variable objReader. Until that happens, objReader doesn't refer to anything.

    Sunday, December 03, 2017 8:45 PM
  • finished blowing leaves, now back to the important stuff...

    I'm unfamiliar with this: IO.Path.Combine(desktop, "Rentals.txt") 

    However, I've placed the file, and have the file name capitalized, unsure why it would not populate the list box.

    Sunday, December 03, 2017 11:08 PM
  • finished blowing leaves, now back to the important stuff...

    I'm unfamiliar with this: IO.Path.Combine(desktop, "Rentals.txt") 

    However, I've placed the file, and have the file name capitalized, unsure why it would not populate the list box.

    Trevor,

    Please make it obvious who you're addressing; we don't all see this forum the same way.

    *****

    If you're unfamiliar with the Path class, then you should spend a little while checking it out:

    https://msdn.microsoft.com/en-us/library/system.io.path(v=vs.110).aspx

    Do note though that it's all string manipulation; no files (or paths) are actually being tested. One of the methods will combine a path (using the appropriate separator, as required) and that's what you're dealing with:

    IO.Path.Combine


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, December 03, 2017 11:14 PM
  • However, I've placed the file, and have the file name capitalized, unsure why it would not populate the list box.

    The path.combine method is the 'correct' way to create a complete path/filename from a string.  In particular, it takes account of the possible difference in separators used in different operating systems, which isn't relevant in this case.  Nonetheless, it is simple and reliable, compared to string concatenation.

    If you stick with the debugging you will be able to confirm that the file path and name has been constructed properly at the point at which it is actually used.   The next important check point after that is the state of the arrays after the file read has been completed.

    Monday, December 04, 2017 12:27 AM
  • Frank, pardon me, I thought when you clicked reply it attached to that post like other forums.

    There are two forms in the project. I know the program doesn't make much sense, but it aims to show us how to create a menu strip and have a new window pop up. It displays the city, rent. 

    I'm trying to build the program one section at a time to make sure it works. I don't get why the txt file won't load. There is an array sort on the example for the second form.

    What is required to get the txt file to populate?

     Private Sub frmDisplayInventory_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'The frmDisplayInventory load event is a second form that 
            'displays the sorted inventory items.
            Dim strItem As String
    
            'Sorts the _strInventoryItem array
            Array.Sort(frmDepreciation._strInventoryItem)
    
            'Displays the _strInventoryItem array.
            For Each strItem In frmDepreciation._strInventoryItem
                lstDisplay.Items.Add(strItem)
            Next
    
        End Sub




    • Edited by trevorpan Monday, December 04, 2017 12:55 AM
    Monday, December 04, 2017 12:48 AM
  • Trevor,

    I'm taking off for the night but this is getting longer in tooth as we go.

    Ultimately, please put in a breakpoint and use it for what it does: When you step into the code, on each line which is executed (keep in mind you're "one line behind" until you actually step), hover your mouse over any variable which is then in scope.

    You're making an assumption but you haven't confirmed it.

    I suspect that you'll find that your assumptions aren't correct so at that point, find out why not.

    *****

    Following that we can talk about sending information to another form and/or getting information back (if applicable) but the two don't currently have anything to do with each other.

    You're in good hands with Acamar - he won't lead you astray.

    I'll be back tomorrow (U.S. CST).


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Monday, December 04, 2017 12:55 AM
  • Hi Frank,

    Never felt Acamar was leading me astray.

    I've read 517 pages of Hoisington's book, and have concepts, but not craft. I can see this will take a long time to be fluent.

    From what I gather using Step In, the 'System.FormatException' was thrown. Something's wrong with how the data is stored, or retrieved. 

    Monday, December 04, 2017 1:32 AM
  • From what I gather using Step In, the 'System.FormatException' was thrown. Something's wrong with how the data is stored, or retrieved. 

    That error should have appeared in ordinary execution, but it will almost certainly tell you what the problem is.   What is the full message, what line of code does it occur at, and what are the values of the variables used in that line?

    /edit
    It's almost certainly this line:
    _decRentAmount(intCount) = Convert.ToDecimal(objReader.ReadLine())

    You could change that to:

    Dim strTemp as String = objReader.ReadLine()
    _decRentAmount(intCount) = Convert.ToDecimal(strTemp)

    so that you can see what is actually being read from file.   It could be that it's reading the wrong line, or that there are unexpected additional characters in the line.

    • Edited by AcamarMVP Monday, December 04, 2017 3:57 AM
    Monday, December 04, 2017 3:53 AM
  • Hi Frank,

    Never felt Acamar was leading me astray.

    I've read 517 pages of Hoisington's book, and have concepts, but not craft. I can see this will take a long time to be fluent.

    From what I gather using Step In, the 'System.FormatException' was thrown. Something's wrong with how the data is stored, or retrieved. 

    I suggest that you take it one bit at a time.

    Forget everything about the program overall and for now, focus on this:

    You have a text file which has x number of lines. For each line where there's a city name, the following line has a numeric string. Please do remember that no matter what, it's not a numeric value (yet); it's a string - so it's up to you to make the conversion.

    The goal at this stage is to read that text file and somehow store those values. Encapsulation is the best way - whether you do it via a class, a structure (not a good choice but it'll work) or even a datatable, something needs to relate a particular city with its respective numeric value.

    After that, close the file and dispose the reader.

    If you get it that far then you're miles ahead of where you are now.

    *****

    Let me add this: It's a temptation to use a control for your "means of encapsulation". Don't go down that road; it's a poor choice for many reasons.

    Chime back in with your ideas of how you'll get the data from the file into *something* that you can then later use in the program and we'll go from there.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Monday, December 04, 2017 12:52 PM
  • Hi Frank,

    Thank you.

    Let me noodle on this a bit. The encapsulation is different from the text book example. But I think this will be good to study more. 


    Monday, December 04, 2017 2:31 PM
  • Hi Acamar,

    I put in this Dim and code change, when stepping in the Error List box says:

    Error BC32000 Local variable 'objReader' cannot be referred to before it is declared.
     

    With the original code (above), fashioned after the example in the book, there are no errors in the Error List box, the format exception noted earlier occurred in the Autos box.

    Using Visual Studio 2017.

    Is there not a proper declaration for the array? Perhaps some spaces in the file, or something? Seems like if there was a space, it would at least populate San Francisco...

    Monday, December 04, 2017 2:48 PM

  •  

    With the original code (above), fashioned after the example in the book, there are no errors in the Error List box, the format exception noted earlier occurred in the Autos box.


    i see I've come late to this party, and hate to start another tangential
    train of thought to the discussion - but ...

    I'm not comfortable with the way the thread seems to have digressed away
    from the original code posted and the problem observed when using it.
    While many/most/all of the suggestions offered to date are meritorious,
    I personally would prefer to stick with the original code until a
    definitive answer has been arrived at, preferably via rigorous analysis
    rather than trial and error. Once that goal has been realized then
    certainly adopt the suggestions already made to improve your code.

    Please try this:

    (1) Create a new VB project. Make it a console project, not WinForms.

    (2) Use the following code in its entirety, unaltered.

    (3) Place the rentals.txt file in the ...\bin\Debug folder.

    (4) Note that in my code example I have omitted the path. When running
        a Debug build from the IDE it should automatically look in that
        folder.
        
    (5) Do a Build. Check for Errors and Warnings. When clean, Run it.

    The program should read all lines from the file, store them in a List,
    and display that list on the console.

    Option Strict On
    
    Module Module1
    
        Sub Main()
            Dim ob As New frmApartmentRental ' ***
            ob.frmApartmentRental_Load() '  ***
        End Sub
    
    End Module
    
    Public Class frmApartmentRental
        'Class level variables.
        Public Shared _intSizeOfArray As Integer = 9
        Private _strCityName(_intSizeOfArray) As String
        Private _decRentAmount(_intSizeOfArray) As Decimal
    
        ' Private Sub frmApartmentRental_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Public Sub frmApartmentRental_Load() '  ***
            Dim objReader As IO.StreamReader
            'Dim strLocationAndNameOfFile As String = "C:\Users\Trevor Pan\source\repos\Apartment Rental By City\Apartment Rental By City\bin\Debug\rentals.txt"
            Dim strLocationAndNameOfFile As String = "rentals.txt" '  ***
            Dim intCount As Integer = 0
            Dim intFill As Integer
            Dim strFileError As String = "The file is not available. Restart when the file is available."
    
            Dim Lstr = New List(Of String) '  ***
    
            'Verify the file exists.
            If IO.File.Exists(strLocationAndNameOfFile) Then
                objReader = IO.File.OpenText(strLocationAndNameOfFile)
                'Read the file line by line until the file is completed.
                Do While objReader.Peek <> -1
                    _strCityName(intCount) = objReader.ReadLine()
                    _decRentAmount(intCount) = Convert.ToDecimal(objReader.ReadLine())
                    intCount += 1
    
                Loop
                objReader.Close()
    
                'The ListBox object is filled with the City Names
                For intFill = 0 To (_strCityName.Length - 1)
                    'lstCities.Items.Add(_strCityName(intFill))
                    Lstr.Add(_strCityName(intFill)) '  ***
                Next
    
                For Each s In Lstr '  ***
                    Console.WriteLine(s) '  ***
                Next '  ***
                Console.ReadLine() '  ***
    
            Else
                MsgBox(strFileError, , "Error")
                'Close()
            End If
        End Sub
    
    End Class
    

    ' Output

    San Francisco
    New York City
    Boston
    Jersey City
    Washington D.C.
    Los Angeles
    San Jose
    Stamford
    Miami
    Seattle

    If all goes as expected, then take a closer look at how/where you are
    adding the lines to a listbox. Is it the correct one? If it is, try
    doing a Refresh() after all lines have been added to force it to redraw.
    e.g. - lstCities.Refresh()

    - Wayne

    Monday, December 04, 2017 7:22 PM
  • With the original code (above), fashioned after the example in the book, there are no errors in the Error List box, the format exception noted earlier occurred in the Autos box.

    You are jumping ahead. 

    You first need to confirm what the error was, the line at which it occurred and the values of the variables on that line.   My suggested was based on an assumption, and if that assumption is wrong then the suggestion is irrelevant.  If the error was in the Autos box then that is not an error in your application. The change I suggested will make debugging a little easier, but otherwise wouldn't change anything.   You should just continue with the single stepping, examining your variables, until the first pair of lines is read, and you can examine the first elements of the two arrays.

    Monday, December 04, 2017 8:09 PM
  • Hi Wayne,

    Created a console project. Have never used this type of project before. Have no idea how to use it.

    This code below is a working example project in the book. I certainly appreciate everyone's help. 

    Could you look at this, and the above original code? I feel like i've got a variable missing, but am too inexperienced to know where I'm screwing up.

    Option Strict On
    
    
    Public Class frmDepreciation
        'Class level variables.
        Private _intLifeOfItems As Integer = 5
        Public Shared _intSizeOfArray As Integer = 7
        Public Shared _strInventoryItem(_intSizeOfArray) As String
        Private _strItemId(_intSizeOfArray) As String
        Private _decInitialPrice(_intSizeOfArray) As Decimal
        Private _intQuantity(_intSizeOfArray) As Integer
    
        Private Sub frmDepreciation_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'The frmDepreciation load event reads the inventory text file and
            'fills the listbox object with the inventory items.
    
            'Initialize an instance of the StreamReader object and declare variables.
            Dim objReader As IO.StreamReader
            Dim strLocationAndNameOfFile As String = "inventory.txt"
            Dim intCount As Integer = 0
            Dim intFill As Integer
            Dim strFileError As String = "The file is not available. Restart when the file is available."
    
            'Verify the file exists.
            If IO.File.Exists(strLocationAndNameOfFile) Then
                objReader = IO.File.OpenText(strLocationAndNameOfFile)
                'Read the file line by line until the file is completed.
                Do While objReader.Peek <> -1
                    _strInventoryItem(intCount) = objReader.ReadLine()
                    _strItemId(intCount) = objReader.ReadLine()
                    _decInitialPrice(intCount) = Convert.ToDecimal(objReader.ReadLine())
                    _intQuantity(intCount) = Convert.ToInt32(objReader.ReadLine())
                    intCount += 1
    
                Loop
                objReader.Close()
    
                'The ListBox object if filled with the Inventory ID's
                For intFill = 0 To (_strItemId.Length - 1)
                    lstInventoryId.Items.Add(_strItemId(intFill))
                Next
            Else
                MsgBox(strFileError, , "Error")
                Close()
            End If
        End Sub

    Wednesday, December 06, 2017 7:07 PM
  • Trevor,

    You're wasting your time on a console application. Your project is a WinForms project so focus on that.

    To emulate where you were Monday, try this in a new WinForms project please:

    Public Class Form1
        Private _text As String
    
    
    
        Private Sub _
            Form1_Load(sender As Object, _
                       e As EventArgs) _
                       Handles MyBase.Load
    
            Dim s() As String = _
                {"San Francisco", "4570", "New York City", _
                 "4310", "Boston", "3200", "Jersey City", "3200", _
                 "Washington D.C.", "3000", "Los Angeles", "2600", _
                 "Stamford", "2450", "Miami", "2400", "Seattle", "2210"}
    
            _text = String.Join(vbCrLf, s)
    
            GetData()
    
        End Sub
    
    
    
        Private Sub GetData()
    
            For Each s As String In _text.Split(New String() {vbCrLf}, StringSplitOptions.None)
                Stop
    
                ' At each "Stop" above, the variable "s"
                ' has the string value of what it read
                ' from the class-scoped variable named
                ' "_text".
                ' 
                ' This is the same thing that you're
                ' dealing with in your actual program;
                ' a console application isn't of any
                ' value at all here - your example is
                ' a WinForms project.
            Next
    
        End Sub
    End Class

    It's not reading a file and my "for each" is different than what you'd do if you were reading a file line by line but the concept is the same; on each one read, the entry alternates between a city name and a numeric value.

    How are you going to store each logical entry so that you can use them later in your program?

    Solve that and you'll be most of the way to where you want to be.


    "A problem well stated is a problem half solved.” - Charles F. Kettering



    Wednesday, December 06, 2017 7:40 PM
  • Created a console project. Have never used this type of project before. Have no idea how to use it.

    This code below is a working example project in the book. I certainly appreciate everyone's help. 

    Don't even consider a console project.  It will be too difficult to debug, and it will add nothing to what you need to know to program in .Net.   There was nothing wrong with the original project that some straightforward analysis could not fix, and once that is sorted you will have a basis for tackling any sort of file processing.   Jumping around amongst different projects will make it very difficult to move forward with any of them.

    Wednesday, December 06, 2017 7:58 PM

  • Don't even consider a console project.  It will be too difficult to debug, and it will add nothing to what you need to know to program in .Net.   There was nothing wrong with the original project that some straightforward analysis could not fix, and once that is sorted you will have a basis for tackling any sort of file processing.   Jumping around amongst different projects will make it very difficult to move forward with any of them.

    I agree.

    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Wednesday, December 06, 2017 8:00 PM
  • Hi Wayne,

    Created a console project. Have never used this type of project before. Have no idea how to use it.


    If it Builds without errors, all you have to do is press Ctrl-F5 and
    it should read the file and display the contents in a console window.

    The point of this exercise was simply to satisfy you that your original
    code for reading the file and processing the lines does in fact work.
    Isolating the file reading from other tasks as a "proof of concept"
    exercise should help narrow your focus on the source of your bug.

    Before looking at embellishing or expanding your program, you should
    establish clearly whether you are in fact having issues reading the
    file. Or does the list not show for other reasons? e.g. - Wrong
    listbox being used, listbox properties not set correctly, listbox
    not refreshing/updating when needed, etc.

    Using the IDE debugger as suggested is the preferred way to do
    debugging, but it can introduce a whole new set of tasks that
    have to be learned while trying to locate the bug in your code
    for this assignment. Once mastered it will expedite debugging,
    but for beginners it may sometimes add another layer of confusion.
    Using "old school" debugging methods - isolating parts of code in
    discrete modules, adding temporary displays of variables, etc. often
    can be easier for a novice to exploit and understand in a narrow
    timeframe..

    - Wayne

    Thursday, December 07, 2017 12:44 AM
  • Hi Wayne,

    This code below is a working example project in the book. I certainly appreciate everyone's help. 

    Could you look at this, and the above original code? I feel like i've got a variable missing, but am too inexperienced to know where I'm screwing up.

    There does not appear to be anything fundamentally wrong with the original
    code you posted, as far as it can be vetted without seeing the entire
    project. For example:

    Create a new project with just a listbox on the form.

    Add your original code to the form load event changing
    the name of the listbox accordingly.

    Build and if clean Run.

    It should show:

    - Wayne

    Thursday, December 07, 2017 1:38 AM
  • There does not appear to be anything fundamentally wrong with the original code you posted, as far as it can be vetted without seeing the entire project.

    Yes.   That's why changing the code is not a useful procedure at this stage.  All that's needed is for OP to step through the code carefully and find out at what point it is not doing what it appears it ought to be doing.

    Thursday, December 07, 2017 1:50 AM
  • Hi Acamar,

    I've posted every step-in taken procedure. Nothing thus far stuck out as to why it is not displaying.

    Thursday, December 07, 2017 4:04 PM
  • Hi Wayne, 

    I've got no idea why you can get it to show, and mine doesn't show. There's nothing in the code beyond the: Private Sub FrmApartmentRental_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    I think I'm just going to proceed, and turn it in not working. Appreciate you and everyone taking time to help. 

    Best regards,

    Trevor

    Thursday, December 07, 2017 4:06 PM
  • I've got no idea why you can get it to show, and mine doesn't show. There's nothing in the code beyond the: Private Sub FrmApartmentRental_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    I think I'm just going to proceed, and turn it in not working.


    As a last-ditch attempt to solve the mystery, you could create a ZIP file
    containing the entire project directories and post it to

    https://onedrive.live.com/about/en-us/

    You can then post a link to the archive here so we can examine all of
    the project settings, etc. You can/should delete the archive or invalidate
    the link to it after we have retrieved the ZIP. (To prevent others from
    plagiarizing your work.)

    - Wayne

    Thursday, December 07, 2017 4:41 PM
  • Hi Wayne,

    First time trying this. https://1drv.ms/f/s!AlfDKri1puMNaeK9hD7s8zZ8cN8

    Best regards,

    Trevor

    Thursday, December 07, 2017 5:24 PM
  •             Do While objReader.Peek <> -1
                    _strCityName(intCount) = objReader.ReadLine()
                    _decRentAmount(intCount) = Convert.ToDecimal(objReader.ReadLine())
                    _decRentAmount(intCount) = Convert.ToDecimal(objReader.ReadLine())
                    intCount += 1
    
                Loop
    

    Why do you have the code to read the number line twice?

    - Wayne

    Thursday, December 07, 2017 6:06 PM
  • Hi Wayne,

    That's a recent mistake, at one point above I was asked to try:

    Dim strTemp as String = objReader.ReadLine()
    _decRentAmount(intCount) = Convert.ToDecimal(strTemp)

    I changed the name back to the original after it did not work, but did not delete it by mistake. However, that is not the issue from what I gather.

    Do you find this to be correct?


    Thursday, December 07, 2017 6:27 PM

  • That's a recent mistake, at one point above I was asked to try:

    Dim strTemp as String = objReader.ReadLine()
    _decRentAmount(intCount) = Convert.ToDecimal(strTemp)

    I changed the name back to the original after it did not work, but did not delete it by mistake. However, that is not the issue from what I gather.


    You must do that read only once, not twice.

    Your problems are being caused by the data file contents.

    It has too many linefeed characters, some before/after CR/LF pairs.
    Also extra LF characters *at the end of the file* are causing the program
    to skip the loading of the listbox code.

    Recreate the data file manually using Notepad.

    Do not add extra blank lines at the end.

    - Wayne

    Thursday, December 07, 2017 8:00 PM
  • I also noticed that at the end of Form1.vb you have:

        Private Sub btnComputeAvgRental_Click(sender As Object, e As EventArgs) Handles btnComputeAvgRental.Click
    
    End Class
    

    You are missing an End Sub:

        Private Sub btnComputeAvgRental_Click(sender As Object, e As EventArgs) Handles btnComputeAvgRental.Click
    
        End Sub
        
    End Class
    

    - Wayne

    Thursday, December 07, 2017 8:06 PM
  • Recreate the data file manually using Notepad.

    Actually using WordPad would be better as you will be able to see the
    extra linefeeds and delete the blank lines that they cause.

    - Wayne

    • Marked as answer by trevorpan Thursday, December 07, 2017 8:48 PM
    Thursday, December 07, 2017 8:20 PM
  • 

    Wayne is a genius.

    How could that be? I pulled the file from the repository for the book. Shouldn't it have at least populated San Francisco? 

    Earlier post Monday, December 04, 2017 2:48 PM was close to the solution but no cigar. 


    • Marked as answer by trevorpan Thursday, December 07, 2017 8:48 PM
    • Unmarked as answer by trevorpan Thursday, December 07, 2017 8:48 PM
    • Edited by trevorpan Thursday, December 07, 2017 8:50 PM
    Thursday, December 07, 2017 8:35 PM
  • 

    I pulled the file from the repository for the book. Shouldn't it have at least populated San Francisco?

    It looks like the original data file had just 0x0A (LineFeed) characters
    at he end of the lines. That's typical of files created on Unix/Linux.
    But Windows/DOS uses CR/LF (0x0D0A). At some point the file was converted
    to have (some) CRLF pairs, but the solitary 0x0A characters were still
    there as well.

    >Shouldn't it have at least populated San Francisco?

    The program will have populated the array, but as soon as problems
    occurred - either with Convert failures or array overruns - then
    code execution in that module will abort before it ever gets to the
    point of Adding the strings from the array into the listbox.

    - Wayne

    P.S. - Did Jersey City lose its franchise?

    Thursday, December 07, 2017 8:52 PM
  • Wayne, Jersey City lost it's franchise - briefly.

    Thank you for your help and everyone else's. A great programming win here.

    Thursday, December 07, 2017 9:00 PM
  • Got this to work, too. Awesome.
    Thursday, December 07, 2017 9:10 PM
  • Got this to work, too. Awesome.

    Trevor,

    I'm glad that you found the issue but something isn't right in what you show above. Either that or the data changed from what you originally showed?

    San Francisco
    4570
    New York City
    4310
    Boston
    3200
    Jersey City
    3200
    Washington D.C.
    3000
    Los Angeles
    2600
    San Jose
    2580
    Stamford
    2450
    Miami
    2400
    Seattle
    2210

    If you recall, I said several nights ago that using two disparate collections relying only on the index to keep them together was a bad idea. My guess in the above is you sorted those controls which then destroys that weak link between them.

    Encapsulation is a much better way.

    For what it's worth...


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Thursday, December 07, 2017 9:28 PM