Results 1 to 17 of 17

Thread: Opening a file to display text?

  1. #1

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    56

    Question Opening a file to display text?

    I am new to opening files and using "StreamReader", when I try to open up a file it displays all of the numbers as 0 instead of what they are, and I am not sure where my mistake is.

    Also I am pretty sure I did not do saving right either..

    Code:
    Imports System.IO
    
    Public Class ClassAverage
        Dim fileWriter As StreamWriter ' writes data to a text file
        Dim FileName As String ' name of file to save data
        Enum GradesFiles
            Grades
        End Enum
        ' places a grade in the gradesListBox
        Private Sub submitGradeButton_Click(ByVal sender As System.Object,
           ByVal e As System.EventArgs) Handles submitGradeButton.Click
    
            ' if the user entered a grade
            If gradeTextBox.Text <> String.Empty Then
                ' add the grade to the end of the gradesListBox
                gradesListBox.Items.Add(gradeTextBox.Text)
                gradeTextBox.Clear() ' clear the gradeTextBox
            End If
    
            gradeTextBox.Focus() ' gives the focus to the gradeTextBox
        End Sub ' submitGradeButton_Click
    
        ' calculates the class average based on the grades in gradesListBox
        Private Sub calculateAverageButton_Click(ByVal sender As System.Object,
           ByVal e As System.EventArgs) Handles calculateAverageButton.Click
    
            Dim total As Integer ' sum of grades entered by user
            Dim gradeCounter As Integer ' counter for grades 
            Dim grade As Integer ' grade input by user
            Dim average As Double ' average of grades
    
            ' initialization phase
            total = 0 ' set total to zero before adding grades to it
            gradeCounter = 0 ' prepare to loop
    
            ' processing phase
            Do While gradeCounter < gradesListBox.Items.Count
                grade = gradesListBox.Items(gradeCounter) ' get next grade
                total += grade ' add grade to total
                gradeCounter += 1 ' add 1 to gradeCounter
            Loop
    
            ' termination phase
            If gradeCounter <> 0 Then
                average = total / gradesListBox.Items.Count ' calculate average
    
                ' display total and average (with two digits of precision)
                classAverageLabel.Text = "Total of the " & gradeCounter &
                   " grade(s) is " & total & vbCrLf & "Class average is " &
                   String.Format("{0:F}", average)
            Else
                classAverageLabel.Text = "No grades were entered"
            End If
        End Sub ' calculateAverageButton_Click
    
        ' clears grades from gradeListBox and results from classAverageLabel
        Private Sub clearGradesButton_Click(ByVal sender As System.Object,
           ByVal e As System.EventArgs) Handles clearGradesButton.Click
    
            gradesListBox.Items.Clear() ' removes all items from gradesListBox
            classAverageLabel.Text = String.Empty ' clears classAverageLabel
        End Sub ' clearGradesButton_Click
    
        Private Sub ExitToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExitToolStripMenuItem.Click
            Me.Close()
        End Sub
    
        Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object,
    ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
    
    
            Dim result As DialogResult
    
            Using fileChooser As New OpenFileDialog()
                result = fileChooser.ShowDialog()
                FileName = fileChooser.FileName
            End Using
    
            If result <> Windows.Forms.DialogResult.Cancel Then
                submitGradeButton.Enabled = True
                gradeTextBox.Enabled = True
            End If
            DisplayGrades(GradesFiles.Grades)
        End Sub
    
        Sub DisplayGrades(ByVal gradesFiles As GradesFiles)
            Dim fileReader As StreamReader = Nothing
    
            fileReader = New StreamReader(FileName)
            Do While Not fileReader.EndOfStream
                Dim line As String = fileReader.ReadLine()
                Dim Grades As Integer
    
                If displayif(Grades, gradesFiles) Then
                    gradesListBox.Items.Add(Grades & vbCrLf)
                End If
            Loop
        End Sub
        Function displayif(ByVal Grades As Integer,ByVal type As GradesFiles) As String
    
            If Grades >= 0 AndAlso type = GradesFiles.Grades Then
                Return True
            End If
    
            Return False
    
        End Function
    
        Private Sub SaveToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SaveToolStripMenuItem.Click
            Dim result As DialogResult
            Dim filename As String
            Using fileChooser As New SaveFileDialog()
                result = fileChooser.ShowDialog()
                filename = fileChooser.FileName
            End Using
    
            If result <> Windows.Forms.DialogResult.Cancel Then
                Try
    
                    fileWriter = New StreamWriter(filename, True)
                Catch ex As IOException
                    MessageBox.Show("Error Opening File", "Error",
                      MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
    
            End If
        End Sub
    End Class
    Thanks

  2. #2
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Opening a file to display text?

    vb Code:
    1. gradeCounter = 0 ' prepare to loop
    2.  
    3.         ' processing phase
    4.         Do While gradeCounter < gradesListBox.Items.Count
    5.             grade = gradesListBox.Items(gradeCounter) ' get next grade
    6.             total += grade ' add grade to total
    7.             gradeCounter += 1 ' add 1 to gradeCounter
    8.         Loop

    Looks like gradeCounter starts at 0, so therefore 0 will always be less than the item count in listbox.

    Loop never happens.
    -
    Good Luck!

  3. #3

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    56

    Re: Opening a file to display text?

    Quote Originally Posted by proneal View Post
    vb Code:
    1. gradeCounter = 0 ' prepare to loop
    2.  
    3.         ' processing phase
    4.         Do While gradeCounter < gradesListBox.Items.Count
    5.             grade = gradesListBox.Items(gradeCounter) ' get next grade
    6.             total += grade ' add grade to total
    7.             gradeCounter += 1 ' add 1 to gradeCounter
    8.         Loop

    Looks like gradeCounter starts at 0, so therefore 0 will always be less than the item count in listbox.

    Loop never happens.
    -
    Good Luck!
    Well everything works fine in the program except for opening a file and saving which is further down in the code, at the bottom.

  4. #4
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Opening a file to display text?

    Ok, I will look into that. Sorry. I eye balled it and sure enoguh did the backward thing in my head once again.
    Sorry and please pay no mind to the shclepp in the room

  5. #5
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Opening a file to display text?

    vb Code:
    1. Function displayif(ByVal Grades As Integer,ByVal type As GradesFiles) As String
    2.  
    3.         If Grades >= 0 AndAlso type = GradesFiles.Grades Then
    4.             Return True
    5.         End If
    6.  
    7.         Return False
    8.  
    9.     End Function

    iS Grades actually passed a value here?
    If not, it will be -1 I think.
    Place breakpoint there to see it's value.
    then report back here
    -
    Good Luck!~

  6. #6

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    56

    Re: Opening a file to display text?

    Quote Originally Posted by proneal View Post
    vb Code:
    1. Function displayif(ByVal Grades As Integer,ByVal type As GradesFiles) As String
    2.  
    3.         If Grades >= 0 AndAlso type = GradesFiles.Grades Then
    4.             Return True
    5.         End If
    6.  
    7.         Return False
    8.  
    9.     End Function

    iS Grades actually passed a value here?
    If not, it will be -1 I think.
    Place breakpoint there to see it's value.
    then report back here
    -
    Good Luck!~
    Hmmm it says grades = 0 at the breakpoint why?

    Edit, so I need to pass it a value?
    Last edited by Josh704; Feb 9th, 2012 at 07:20 PM.

  7. #7
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Opening a file to display text?

    Ok what about this?

    Breakpoint here:
    vb Code:
    1. fileWriter = New StreamWriter(filename, True)

    What data is being saved here?

  8. #8

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    56

    Re: Opening a file to display text?

    Quote Originally Posted by proneal View Post
    Ok what about this?

    Breakpoint here:
    vb Code:
    1. fileWriter = New StreamWriter(filename, True)

    What data is being saved here?
    I think you were right before about the value of grades, I googled a little and found someone else with the same problem and he answered it by assigning grades as integer a value, but I'm not exactly sure what that means

  9. #9
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Opening a file to display text?

    I'm trying to see without using the IDE and going through adding all the right names to controls...
    But I really don't see where you would loop through the values in the Lisbox -to then save those values into the text file that is being used for the Save toolboxmenu function.

    It would be something similar to this:
    vb Code:
    1. For i As Integer = 0 To gradesListBox.Items.Count - 1
    2.                                 Debug.Write(gradesListBox.Items(i).ToString & vbNewLine)
    3.             Next

    Place that in the save code and see if it outputs to your debug window - the Output window...
    -

  10. #10

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    56

    Re: Opening a file to display text?

    Quote Originally Posted by proneal View Post
    I'm trying to see without using the IDE and going through adding all the right names to controls...
    But I really don't see where you would loop through the values in the Lisbox -to then save those values into the text file that is being used for the Save toolboxmenu function.

    It would be something similar to this:
    vb Code:
    1. For i As Integer = 0 To gradesListBox.Items.Count - 1
    2.                                 Debug.Write(gradesListBox.Items(i).ToString & vbNewLine)
    3.             Next

    Place that in the save code and see if it outputs to your debug window - the Output window...
    -
    Yeah they went into the debug window

  11. #11
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Opening a file to display text?

    vb Code:
    1. fileWriter = New StreamWriter(filename, False)
    2.             For i As Integer = 0 To gradesListBox.Items.Count - 1
    3.                 fileWriter.WriteLine(gradesListBox.Items(i).ToString)
    4.                      Next
    5.             fileWriter.Close()

    then did you add this to the code?

  12. #12
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Opening a file to display text?

    You would have to modify your Open code.
    Something like this
    vb Code:
    1. Sub DisplayGrades(ByVal gradesFiles As GradesFiles)
    2.         Dim fileReader As StreamReader = Nothing
    3.  
    4.         fileReader = New StreamReader(FileName)
    5.         Dim Grades As Integer = 0
    6.         Do While Not fileReader.EndOfStream
    7.             Dim line As String = fileReader.ReadLine()
    8.  
    9.             Grades = +1
    10.             If displayif(Grades, gradesFiles) Then
    11.                 gradesListBox.Items.Add(line)
    12.             End If
    13.         Loop
    14.         fileReader.Close()
    15.         fileReader = Nothing
    16.  
    17.     End Sub

    The way you had it before never iterated through the text file line by line-
    -
    It's how we learn

    edit: I dont think displayif is needed at all. Not sure why it's there.

    Good Luck!
    Last edited by proneal; Feb 9th, 2012 at 10:42 PM.

  13. #13

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    56

    Re: Opening a file to display text?

    Quote Originally Posted by proneal View Post
    You would have to modify your Open code.
    Something like this
    vb Code:
    1. Sub DisplayGrades(ByVal gradesFiles As GradesFiles)
    2.         Dim fileReader As StreamReader = Nothing
    3.  
    4.         fileReader = New StreamReader(FileName)
    5.         Dim Grades As Integer = 0
    6.         Do While Not fileReader.EndOfStream
    7.             Dim line As String = fileReader.ReadLine()
    8.  
    9.             Grades = +1
    10.             If displayif(Grades, gradesFiles) Then
    11.                 gradesListBox.Items.Add(line)
    12.             End If
    13.         Loop
    14.         fileReader.Close()
    15.         fileReader = Nothing
    16.  
    17.     End Sub

    The way you had it before never iterated through the text file line by line-
    -
    It's how we learn

    edit: I dont think displayif is needed at all. Not sure why it's there.

    Good Luck!
    Thanks ill try it when i get back, I appreciate all your help. I am still learning Haha.

  14. #14

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    56

    Re: Opening a file to display text?

    Quote Originally Posted by proneal View Post
    You would have to modify your Open code.
    Something like this
    vb Code:
    1. Sub DisplayGrades(ByVal gradesFiles As GradesFiles)
    2.         Dim fileReader As StreamReader = Nothing
    3.  
    4.         fileReader = New StreamReader(FileName)
    5.         Dim Grades As Integer = 0
    6.         Do While Not fileReader.EndOfStream
    7.             Dim line As String = fileReader.ReadLine()
    8.  
    9.             Grades = +1
    10.             If displayif(Grades, gradesFiles) Then
    11.                 gradesListBox.Items.Add(line)
    12.             End If
    13.         Loop
    14.         fileReader.Close()
    15.         fileReader = Nothing
    16.  
    17.     End Sub

    The way you had it before never iterated through the text file line by line-
    -
    It's how we learn

    edit: I dont think displayif is needed at all. Not sure why it's there.

    Good Luck!
    Wow that worked perfectly, thank you so much for all your help, I know it is probably hard to help me! If you have the time do you think you could comment what each line does? I am not sure what or why it works differently now ha.

  15. #15
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Opening a file to display text?

    Hi OP, I will try come back later and clean up that code I gave. It is real messy.
    If I try to explain as it is, It would sound as stupid as it looks!

    -
    Glad it helped though!

  16. #16

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    56

    Re: Opening a file to display text?

    Quote Originally Posted by proneal View Post
    Hi OP, I will try come back later and clean up that code I gave. It is real messy.
    If I try to explain as it is, It would sound as stupid as it looks!

    -
    Glad it helped though!

    Okay thanks again! Trying to get used to saving and opening files, I got the save to kind of work.

  17. #17
    Fanatic Member proneal's Avatar
    Join Date
    May 2011
    Posts
    762

    Re: Opening a file to display text?

    Save Kind of works?
    Grades is being used as Numeric Counter and the way I inserted it last night is wrong

    It should be
    vb Code:
    1. Grades += 1

    -
    Your Save code should be similar to this:
    vb Code:
    1. Dim result As DialogResult
    2.         Dim filename As String
    3.         Using fileChooser As New SaveFileDialog()
    4.             result = fileChooser.ShowDialog()
    5.             filename = fileChooser.FileName
    6.         End Using
    7.  
    8.         If result <> Windows.Forms.DialogResult.Cancel Then
    9.              Try
    10.  
    11.             fileWriter = New StreamWriter(filename, False)
    12.  
    13.             For i As Integer = 0 To gradesListBox.Items.Count - 1
    14.                 fileWriter.WriteLine(gradesListBox.Items(i).ToString)
    15.             Next
    16.  
    17.             fileWriter.Close()
    18.            
    19.            Catch ex As IOException
    20.             MessageBox.Show("Error Opening File", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    21.            End Try
    22.  
    23.         End If

    In a few places you are using KEYWORDS as variables within your routines.
    Filename is declared Form wide, but you should not use naming conventions the way you are doing.

    For unstance this function:
    vb Code:
    1. Function displayif(ByVal Grades As Integer, ByVal type As GradesFiles) As String

    You declare type as a TYPE and that is a poor way to do this. Shouldn't be done like this.

    Displayif and Displaygrades are two functions tat really do not serve any useful purpose so you might want to recode without using those.


    If you were using a Listview and wanted to put up the grade in one column and the Letter grade corresponding to it's numerical value in another column, then using some interior function would serve a useful purpose, but you are only dealing with one value, hence one numerical grade value, which is easy to work with to fill up Listbox with values.

    Starting a routine this way:
    Dim fileReader As StreamReader = Nothing

    fileReader = New StreamReader(FileName)
    it is not having to be written this way.
    Try to remove these two lines and make it one line of code. However, it is in the DisplayGrades routine, so move that one-liner into the Open code along with all the rest of DisplayGrades code.

    It would make Open code to look like this:

    vb Code:
    1. Dim result As DialogResult
    2.  
    3.         Using fileChooser As New OpenFileDialog()
    4.             result = fileChooser.ShowDialog()
    5.             FileName = fileChooser.FileName
    6.         End Using
    7.  
    8.         If result <> Windows.Forms.DialogResult.Cancel Then
    9.             submitGradeButton.Enabled = True
    10.             gradeTextBox.Enabled = True
    11.  
    12.             Dim fileReader As StreamReader = New StreamReader(FileName)
    13.  
    14.             Dim Grades As Integer = 0
    15.             Do While Not fileReader.EndOfStream
    16.                 Dim line As String = fileReader.ReadLine()
    17.                 Grades += 1 'increment by one
    18.                 gradesListBox.Items.Add(line)
    19.  
    20.             Loop
    21.  
    22.             fileReader.Close()
    23.  
    24.             If Grades = 0 Then MsgBox("No grades in text")
    25.             ' I added this to show how increment works.
    26.             ' you can store how many Grades in text file within this counter variable
    27.  
    28.         End If

    -
    EDIT: I have to leave office again and I am hoping I didnt leave any errors up here, lol
    let us know how it goes.

    Good luck!
    Last edited by proneal; Feb 10th, 2012 at 04:10 PM.

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