Error in code writing the file and reading it

bong1

New member
Joined
Dec 21, 2008
Messages
1
Programming Experience
Beginner
Hi. I have this code that I am trying to make it work but everytime I debug it it always highlight my write record to file stream under the Add button. I've been working on this for how many days and still can't make it work. Please your help is very much appreciated. This code will allow user to read a file and display the contents on the form using the read button and let the user enter the data for eact textboxes. I know I did everything correct as far as getting the data but still doesn't work. Please help! Thanks a lot.
VB.NET:
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Public Class Form1
    Private fileWriter As StreamWriter 'writes data to text file
    Private output As FileStream 'maintains connection to file
    Private input As FileStream
    Private fileReader As StreamReader
    'event handler for Save Button
    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        'create dialog box enabling user to save file
        Dim fileChooser As New SaveFileDialog()
        Dim result As DialogResult = fileChooser.ShowDialog()
        Dim fileName As String 'name of file to save data

        fileChooser.CheckFileExists = False 'allow user to create file
        'exit event handler if user clicked "Cancel"
        If result = Windows.Forms.DialogResult.Cancel Then
            Return
        End If
        fileName = fileChooser.FileName 'get specified filename
        'show error if user specified invalid file
        If fileName = "" Or fileName Is Nothing Then
            MessageBox.Show("Invalid File Name", "Error", _
            MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            'save file via FileStream if user specified valid file
            Try
                'open file with write access
                output = New FileStream(fileName, FileMode.OpenOrCreate, _
                FileAccess.Write)
                'sets file to where data is written
                fileWriter = New StreamWriter(output)
                'disable Save button and enable Add button
                btnSave.Enabled = False
                btnExit.Enabled = False
                btnRead.Enabled = False
                btnAdd.Enabled = True
                'handle exception if there is a problem opening the file
            Catch ex As IOException
                'notify user if file does not exist
                MessageBox.Show("Error opening file", "Error", _
                MessageBoxButtons.OK, MessageBoxIcon.Error)

            End Try
        End If
    End Sub

    'event handler for Add button

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'store Textbox values string away
        Dim values As String() = GetTextBoxValues()
        'record containing TextBox values to serialize
        Dim record As New Record()
        'store textbox field in record

        'determine whether Textbox ID field is empty
        If values(TextBoxIndices.ID) <> "" Then
            'store TextB ox values in record and serialize record
            Try
                'get ID number value from Textbox
                Dim IDNumber As Integer = _
                Int32.Parse(values(TextBoxIndices.ID))

                'determine whether IDNumber is valid
                If IDNumber > 0 Then
                    'store Textbox field in record
                    record.ID = IDNumber
                    record.FirstName = values(TextBoxIndices.FIRST)
                    record.LastName = values(TextBoxIndices.LAST)
                    record.ClassName = values(TextBoxIndices.CLASSNAME)
                    record.Grade = values(TextBoxIndices.GRADE)

                    'write record to file stream
                    fileWriter.WriteLine(record.ID & "," & record.FirstName & "," & _
                    record.LastName & vbTab & record.ClassName & vbTab & record.Grade)

                Else
                    'notify user if invalid ID Number
                    MessageBox.Show("Invalid ID Number", "Error", _
                    MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If
                'notify user if error occurs in serialization
            Catch ex As IOException
                MessageBox.Show("Error Writing to File", "Error", _
                MessageBoxButtons.OK, MessageBoxIcon.Error)

                'notify user if error occurs regarding parameter format

            Catch ex As FormatException
                MessageBox.Show("invalid Format", "Error", _
                MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
        ClearTextBoxes() ' clear textbox values

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        txtDisplay.Text = "ID" & vbTab & "Name" & vbTab & "Grade" & vbTab & "Class"
        Dim fileChooser As New OpenFileDialog()
        Dim result As DialogResult = fileChooser.ShowDialog()
        Dim fileName As String

        'exit event handler if user clicked the Cancel
        If result = Windows.Forms.DialogResult.Cancel Then
            Return
        End If
        fileName = fileChooser.FileName 'get specified file name
        ClearTextBoxes()

        'show error if user specified invalid file
        If fileName = "" Or fileName Is Nothing Then
            MessageBox.Show("Invalid File Number", "Error", _
            MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            'create FileStream to obtain read access to file
            input = New FileStream(fileName, FileMode.Open, FileAccess.Read)

            'set file from where data is read
            fileReader = New StreamReader(input)
        End If

    End Sub
    Protected TextBoxCount As Integer = 5

    'enumeration constants specify Textbox indices
    Public Enum TextBoxIndices
        ID
        FIRST
        LAST
        CLASSNAME
        GRADE
    End Enum
    'clear all textboxes
    Public Sub ClearTextBoxes()
        'iterate through every Control on form
        For i As Integer = 0 To Controls.Count - 1
            Dim myControl As Control = Controls(i) 'get control
            'determine whether COntrol is TextBox
            If TypeOf myControl Is TextBox Then
                'clear Text property (set to empty sting)
                myControl.Text = ""
            End If
        Next i
    End Sub
    'set text box values to string array values
    Public Sub SetTextBoxValues(ByVal values() As String)
        'determine whether string array has correct length
        If values.Length <> TextBoxCount Then
            'throw exception if not correct length
            Throw New ArgumentException("There must be " & (TextBoxCount + 1) & _
            " strings in the array")
            'set array values if array has correct length
        Else
            'set array values to text box values
            txtID.Text = values(Convert.ToInt32(TextBoxIndices.ID))
            txtFirstName.Text = values(Convert.ToInt32(TextBoxIndices.FIRST))
            txtLastName.Text = values(Convert.ToInt32(TextBoxIndices.LAST))
            txtClassName.Text = values(Convert.ToInt32(TextBoxIndices.CLASSNAME))
            txtGrades.Text = values(Convert.ToInt32(TextBoxIndices.GRADE))
        End If
    End Sub
    'return text box values as string array
    Public Function GetTextBoxValues() As String()
        Dim values(TextBoxCount) As String
        'copy text box fields to string array
        values(Convert.ToInt32(TextBoxIndices.ID)) = txtID.Text
        values(Convert.ToInt32(TextBoxIndices.FIRST)) = txtFirstName.Text
        values(Convert.ToInt32(TextBoxIndices.LAST)) = txtLastName.Text
        values(Convert.ToInt32(TextBoxIndices.CLASSNAME)) = txtClassName.Text
        values(Convert.ToInt32(TextBoxIndices.GRADE)) = txtGrades.Text
        Return values
    End Function

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        'determine whether file exists
        If output IsNot Nothing Then
            Try
                fileWriter.Close() 'close StreamWriter
                output.Close() 'close file
                'notify user of error closing file
            Catch ex As IOException
                MessageBox.Show("Cannot close file", "Error", _
                MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
        Application.Exit()
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub
End Class
 
First up, there's a lot of code there and, if you've highlighted the line that causes the error, I can't see it. Secondly, you haven't old us what the error message is. If there's an error there's an error message, provided to help fix the error. If you want us to fix the error then we need to know where it occurred and why.
 
Back
Top