1.11M Members

Reading from a file into a list box

 
0
 

Here is what I have to do.

this code needs to be modified to be able to enable the user to select a file in which to store grades. The application should allow the user to write any number of grades into that file and it should write one grade per line. Then it has to be modified to allow the user to specify the location and name of the file containing grades. The application should read the grades from the file, then display the total of grades and the class average.

I have it writing to the file fine, but I can't get it to read from a file.

Imports System.IO ' using classes from this namespace

Public Class EnhancedClassAverage
    Dim fileWriter As StreamWriter ' writes data to a text file
    Dim FileName As String ' name of file to save data

    ' opens a file in which grades are stored
    Private Sub NewToolMenuStripItem_Click(ByVal sender As System.Object,
        ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click

        CloseFile() 'ensure that any prior file is closed
        Dim result As DialogResult ' stores reslt of Save dialog

        Using fileChooser As New SaveFileDialog()
            result = fileChooser.ShowDialog()
            FileName = fileChooser.FileName ' get specified file name
        End Using

        If result <> Windows.Forms.DialogResult.Cancel Then
            Try
                ' open or create file for writing
                fileWriter = New StreamWriter(FileName, True)

                ' enable controls
                CloseToolStripMenuItem.Enabled = True
                submitGradeButton.Enabled = True
                gradeTextBox.Enabled = True
            Catch ex As IOException
                MessageBox.Show("Error Opening File", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    End Sub

    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
            Try
                Dim grade As Integer =
                    Convert.ToInt32(gradeTextBox.Text)

                ' add the grade to the end of the gradesListBox
                gradesListBox.Items.Add(gradeTextBox.Text)
                fileWriter.WriteLine(gradeTextBox.Text)
                gradeTextBox.Clear() ' clear the gradeTextBox

            Catch ex As IOException
                MessageBox.Show("Error Writing to File", "Error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If

        gradeTextBox.Focus() ' gives the focus to the gradeTextBox
    End Sub

    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

    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object,
      ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click

        Dim result As DialogResult ' stores reslt of Save dialog

        Using fileChooser As New OpenFileDialog()
            result = fileChooser.ShowDialog()
            FileName = fileChooser.FileName ' get specified file name
        End Using

        If result <> Windows.Forms.DialogResult.Cancel Then
            ' enable controls
            CloseToolStripMenuItem.Enabled = True
            submitGradeButton.Enabled = True
            gradeTextBox.Enabled = True
            displayGradesButton.Enabled = True
        End If
    End Sub
    Private Sub displayGradesButton_Click(ByVal sender As System.Object,
       ByVal e As System.EventArgs) Handles displayGradesButton.Click

        DisplayGrades()
    End Sub

    Sub DisplayGrades()
        Dim fileReader As StreamReader = Nothing

        Try
            fileReader = New StreamReader(FileName)

            Do While Not fileReader.EndOfStream
                Dim line As String = fileReader.ReadLine()
            Loop
        Catch ex As IOException
            MessageBox.Show("Cannot Read File", "Error",
                MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            If fileReader IsNot Nothing Then
                Try
                    fileReader.Close()
                Catch ex As IOException
                    MessageBox.Show("Error Closing File", "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            End If
        End Try
    End Sub

    ' 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

    ' close the currently open file and disable controls
    Private Sub CloseToolStripMenuItem_Click(ByVal sender As System.Object,
       ByVal e As System.EventArgs) Handles CloseToolStripMenuItem.Click

        CloseFile() ' close currently open file
        CloseToolStripMenuItem.Enabled = False
        submitGradeButton.Enabled = False
        gradeTextBox.Enabled = False

    End Sub

    'exit the application
    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object,
        ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click

        CloseFile() ' close the file before teminating application
        Application.Exit() 'terminate the application
    End Sub

    ' close the file
    Sub CloseFile()
        If fileWriter IsNot Nothing Then
            Try
                fileWriter.Close() ' close StreamWriter
            Catch ex As IOException
                MessageBox.Show("Error closing file", "Error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    End Sub
End Class
 
0
 

The easiest way to read in a text file is to do it all at once as in

Dim alltext As String = My.Computer.FileSystem.ReadAllText(filename)
alltext = alltext.Replace(vbLf, "")
Dim lines() As String = alltext.Split(vbCr)

Or you can do it all at once by

Dim lines() As String = My.Computer.FileSystem.ReadAllText(filename).Replace(vbLf, "").Split(vbCr)
 
0
 

Ok, I have it reading in the file now, but the grades all display as 0 instead of what's in the file.

' Exercise 8.2: EnhancedClassAverage.vb
Imports System.IO ' using classes from this namespace

Public Class EnhancedClassAverage
    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

    ' opens a file in which grades are stored
    Private Sub NewToolMenuStripItem_Click(ByVal sender As System.Object,
        ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click

        CloseFile() 'ensure that any prior file is closed
        Dim result As DialogResult ' stores reslt of Save dialog

        Using fileChooser As New SaveFileDialog()
            result = fileChooser.ShowDialog()
            FileName = fileChooser.FileName ' get specified file name
        End Using

        If result <> Windows.Forms.DialogResult.Cancel Then
            Try
                ' open or create file for writing
                fileWriter = New StreamWriter(FileName, True)

                ' enable controls
                CloseToolStripMenuItem.Enabled = True
                submitGradeButton.Enabled = True
                gradeTextBox.Enabled = True
            Catch ex As IOException
                MessageBox.Show("Error Opening File", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    End Sub

    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
            Try
                Dim grade As Integer =
                    Convert.ToInt32(gradeTextBox.Text)

                ' add the grade to the end of the gradesListBox
                gradesListBox.Items.Add(gradeTextBox.Text)
                fileWriter.WriteLine(gradeTextBox.Text)
                gradeTextBox.Clear() ' clear the gradeTextBox

            Catch ex As IOException
                MessageBox.Show("Error Writing to File", "Error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If

        gradeTextBox.Focus() ' gives the focus to the gradeTextBox
    End Sub

    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

    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object,
      ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click

        Dim result As DialogResult ' stores reslt of Open dialog

        Using fileChooser As New OpenFileDialog()
            result = fileChooser.ShowDialog()
            FileName = fileChooser.FileName ' get specified file name
        End Using

        If result <> Windows.Forms.DialogResult.Cancel Then
            ' enable controls
            CloseToolStripMenuItem.Enabled = True
            submitGradeButton.Enabled = True
            gradeTextBox.Enabled = True
        End If
        DisplayGrades(GradesFiles.Grades)
    End Sub

    Sub DisplayGrades(ByVal gradesFiles As GradesFiles)
        Dim fileReader As StreamReader = Nothing


        ' open file for reading
        fileReader = New StreamReader(FileName)

        ' read file and display lines that match the balance type
        Do While Not fileReader.EndOfStream ' while not end of file
            Dim line As String = fileReader.ReadLine() ' read line
            Dim Grades As Integer

            If ShouldDisplay(Grades, gradesFiles) Then
                gradesListBox.Items.Add(Grades & vbCrLf)
            End If
        Loop
    End Sub

    Function ShouldDisplay(ByVal Grades As Integer,
       ByVal type As GradesFiles) As String

        If Grades >= 0 AndAlso type = GradesFiles.Grades Then
            Return True ' record should be displayed
        End If

        Return False
    End Function

    ' 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

    ' close the currently open file and disable controls
    Private Sub CloseToolStripMenuItem_Click(ByVal sender As System.Object,
       ByVal e As System.EventArgs) Handles CloseToolStripMenuItem.Click

        CloseFile() ' close currently open file
        CloseToolStripMenuItem.Enabled = False
        submitGradeButton.Enabled = False
        gradeTextBox.Enabled = False

    End Sub

    'exit the application
    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object,
        ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click

        CloseFile() ' close the file before teminating application
        Application.Exit() 'terminate the application
    End Sub

    ' close the file
    Sub CloseFile()
        If fileWriter IsNot Nothing Then
            Try
                fileWriter.Close() ' close StreamWriter
            Catch ex As IOException
                MessageBox.Show("Error closing file", "Error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    End Sub
End Class
 
0
 

On line 123 you declare Grades as Integer but you never assign it a value. I'm guessing that when you get to

If Grades >= 0 AndAlso type = GradesFiles.Grades Then

that the first part of the If fails because Grades has no value. That would mean the function always returns False. The ShouldDisplay function should really be commented to describe its purpose (input, output, etc). Put a breakpoint at the If and check the value of Grades at that point.

 
0
 

I got it working. As soon as I assigned my Grades Integer a value, it worked. Thank you so much!

Question Answered as of 2 Years Ago by Reverend Jim
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article