Question Load button for simple reading text file

razza311

Member
Joined
Apr 12, 2013
Messages
5
Programming Experience
Beginner
Hey i'm having an issue where i can save the data i enter into the program but i cant load it as the load button doesn't seem to function.
I don't get any error messages when this happens so i'm very confused
here is the code for the save and load button:
    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim SaveFile As New SaveFileDialog
        SaveFile.FileName = ""
        SaveFile.Filter = "Text Files (*.txt)|*.txt"
        SaveFile.Title = "save"
        SaveFile.ShowDialog()
        Try
            Dim write As New System.IO.StreamWriter(SaveFile.FileName)
            write.Write(txtname.Text)
            write.Write(txtcatagory.Text)
            write.Write(txtlocation.Text)
            write.Write(txtprice.Text)
            write.Write(txtorder.Text)
            write.Write(txtstock.Text)
            write.Close()
        Catch ex As Exception


        End Try
    End Sub

And the load button:
    Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
        Dim FILE_NAME As String = "G:\stock.txt"
        Dim objreader As New System.IO.StreamReader(FILE_NAME)
        txtname.Text = objreader.ReadToEnd
        txtcatagory.Text = objreader.ReadToEnd
        txtlocation.Text = objreader.ReadToEnd
        txtorder.Text = objreader.ReadToEnd
        txtprice.Text = objreader.ReadToEnd
        txtstock.Text = objreader.ReadToEnd
        objreader.Close()
    End Sub
 
Last edited by a moderator:
Hi,

A few things for you here:-

1) When you write your information to the file, you write all the information to the same line without any delimiters between each element of data that you are writing to the file. This means that when you read the file later you are not able to split your data into its specific elements. You are going to need to deal with this issue to begin with.

2) You use a Try/Catch block in your Save routine, but you do not do anything if an error does occur during the saving of the file. You need to add something here to make sure you catch any exceptions.

3) In the Load routine, and as long as the Filename of the file to be loaded is correct, you call this statement to load the first textbox:-

VB.NET:
txtname.Text = objreader.ReadToEnd

Due to this, the first TextBox should be filled with the ENTIRE contents of the file since you have called ReadToEnd on the StreamReader. In addition to this and since you have already called ReadToEnd on the StreamReader, the file pointer is now at the END of the file and therefore any further calls to read the file will return nothing.

Have a look at this example as one way to read a file in a structured manner:-

VB.NET:
Using myReader As New IO.StreamReader("c:\yourfilename.txt")
  While Not myReader.EndOfStream
    Dim strFileLine As String = myReader.ReadLine
    'Your code goes here to deal with each line of the file
  End While
End Using

In this case, the StreamReader is enclosed in a Using block to ensure the file is Closed and Disposed of when you have finished reading the file.

I hope that helps.

Cheers,

Ian

BTW, please use the Advanced button to encase any code you post in Code Tags for readability in the future.
 
Hey Ian thanks ill try it out and let you know how it goes, and when you said your code goes here above, do you mean just the parts where i specify the text boxs?
 
Hey i'm having an issue where i can save the data i enter into the program but i cant load it as the load button doesn't seem to function.
I don't get any error messages when this happens so i'm very confused
here is the code for the save and load button:
    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim SaveFile As New SaveFileDialog
        SaveFile.FileName = ""
        SaveFile.Filter = "Text Files (*.txt)|*.txt"
        SaveFile.Title = "save"
        SaveFile.ShowDialog()
        Try
            Dim write As New System.IO.StreamWriter(SaveFile.FileName)
            write.Write(txtname.Text)
            write.Write(txtcatagory.Text)
            write.Write(txtlocation.Text)
            write.Write(txtprice.Text)
            write.Write(txtorder.Text)
            write.Write(txtstock.Text)
            write.Close()
        Catch ex As Exception


        End Try
    End Sub

And the load button:
    Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
        Dim FILE_NAME As String = "G:\stock.txt"
        Dim objreader As New System.IO.StreamReader(FILE_NAME)
        txtname.Text = objreader.ReadToEnd
        txtcatagory.Text = objreader.ReadToEnd
        txtlocation.Text = objreader.ReadToEnd
        txtprice.Text = objreader.ReadToEnd
        txtorder.Text = objreader.ReadToEnd
        txtstock.Text = objreader.ReadToEnd
        objreader.Close()
    End Sub
If you're looking for some code critiquing, there's several improvements I can suggest with this code.
1. You're creating a SaveFileDialog, but you never check it's ShowDialog result, so if the user click's the Cancel button, it will try to write to nowhere (and will cause an exception).
2. You're writing all the values from the textbox's in a single line back to back, no delimiter character(s) or line breaks, so reading the values back will be next to impossible
3. You're reading the entire contents of the file into each textbox, rather than just their original values
4. You're not cleaning up the object's you're making

Here's an example of what I'm talking about, idealy with this type of code you would use both a SaveFileDialog for writing and a OpenFileDialog for reading, I didn't bother adding the OpenFileDialog to the code.
Imports System.IO

Public Class Form1

    Private m_FileName As String = "G:\stock.txt"

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim SaveFile As New SaveFileDialog With {.FileName = m_FileName, .Filter = "Text Files (*.txt)|*.txt", .Title = "save"}
        If SaveFile.ShowDialog(Me) <> DialogResult.Cancel Then
            Dim write As StreamWriter = Nothing
            Try
                write = New StreamWriter(SaveFile.FileName)

                'Write each item to it's own line
                write.WriteLine(txtname.Text)
                write.WriteLine(txtcatagory.Text)
                write.WriteLine(txtlocation.Text)
                write.WriteLine(txtprice.Text)
                write.WriteLine(txtorder.Text)
                write.WriteLine(txtstock.Text)

                'Keep the new filename in a variable
                m_FileName = SaveFile.FileName
            Catch ex As Exception
                MessageBox.Show(ex.ToString, "btnSave", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Finally
                'Clean up writer object
                If write IsNot Nothing Then
                    write.Close()
                    write.Dispose()
                End If
            End Try
        End If

        'Clean up the SaveFileDialog 
        SaveFile.Dispose()
    End Sub

    Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
        If File.Exists(m_FileName) Then
            Dim sr As StreamReader = Nothing
            Try
                sr = New StreamReader(m_FileName)

                'Read each line into the textbox's
                txtname.Text = sr.ReadLine.Trim
                txtcatagory.Text = sr.ReadLine.Trim
                txtlocation.Text = sr.ReadLine.Trim
                txtorder.Text = sr.ReadLine.Trim
                txtprice.Text = sr.ReadLine.Trim
                txtstock.Text = sr.ReadLine.Trim
            Catch ex As Exception
                MessageBox.Show(ex.ToString, "btnLoad", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Finally
                'Clean up reader object
                If sr IsNot Nothing Then
                    sr.Close()
                    sr.Dispose()
                End If
            End Try
        Else
            MessageBox.Show(String.Format("File '{0}' doesn't exist.", m_FileName), "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
    End Sub

End Class
For something like this you need to make sure you read the items from the file in the same order they where written & to get around that you could write the items to an xml file and use an XmlDocument to get the info back. Or write to a database.
 
Thanks.. im having a little problem with the load button, its reading what I have saved but its loading all the data into the text boxes when I want it to go into my listbox where I can display all the data. im using the code written above as a reference. thanks for any help
 
Thanks.. im having a little problem with the load button, its reading what I have saved but its loading all the data into the text boxes when I want it to go into my listbox where I can display all the data. im using the code written above as a reference. thanks for any help
Then change the code I provided to add items from each readline call into the listbox instead of the textboxes.
 
I have no idea how to do that, I don't expect you to write it for me but maybe hints or a guide on how to would be greatly appreciated

I also need the save button to save all the items in the list box, how do I modify the code for this?
 
razza, I left all the hints of how to add items to a listbox in my previous post. If you look at the listbox's properties I'm sure you'll notice there's an Items property and that property has an Add method, so instead of setting the Textbox's Text property, you can use the ListBox.Items.Add() instead.
 
Back
Top