I need some better understanding of File I/O

eclass

Active member
Joined
Jul 6, 2011
Messages
27
Programming Experience
Beginner
ok guys I took a quick break from programming trying to also enjoy my summer...so I have this problem Im trying to read and write to. the pproblem describes customer accounts on which it wants me to create a structure to store data for the customer accounts which include: Last name, First name, Customer Number, Address,City,State, zip, phone number, account balance, Date of Last payment. The problem says the user should be allow to save customer accpunt records to the file and search by last name or customer number and print a report listing all customer records in the file.


heres what I have so far, and I would like to know if Im off to a decent start:
VB.NET:
Option Strict On
Option Explicit On


Imports System.IO


Module modCustomerAccounts
    Public Structure Customers
        Dim LastName As String
        Dim FirstName As String
        Dim CustomerNumber As Integer
        Dim Address As String
        Dim City As String
        Dim State As String
        Dim ZipCode As Integer
        Dim PhoneNumber As Integer
        Dim AccountBalance As Integer
        Dim LastPayment As Date


    End Structure


    Public gCustomer() As Customers
    Public gFileName As String = ""


    Public Sub LoadCustomer(ByVal fileName As String)
        Dim strCustomerLine As String
        Dim CustomerInformation() As String


        gCustomer = Nothing
        If File.Exists(fileName) Then
            Dim sr As New StreamReader(fileName)
            While Not sr.EndOfStream
                strCustomerLine = sr.ReadLine
                CustomerInformation = strCustomerLine.Split(",".ToCharArray)
                AddCustomerInformation(CustomerInformation(0), CustomerInformation(1), CustomerInformation(2), _
                            CustomerInformation(3), CustomerInformation(4), _
                            CustomerInformation(5), CustomerInformation(6), CustomerInformation(7), _
                            CustomerInformation(8), CustomerInformation(9))
            End While
            sr.Close()
            gFileName = fileName


        End If
    End Sub


    Public Sub SaveCustomers(ByVal fileName As String)
        Dim sw As New StreamWriter(fileName)


        For i = 0 To gCustomer.Length - 1
            With gCustomer(i)
                sw.Write(.LastName & ",")
                sw.Write(.FirstName & ",")
                sw.Write(.CustomerNumber & ",")
                sw.Write(.Address & ",")
                sw.Write(.City & ",")
                sw.Write(.State & ",")
                sw.Write(.ZipCode & ",")
                sw.Write(.PhoneNumber & ",")
                sw.Write(.AccountBalance & ",")
                sw.Write(.LastPayment & ",")
            End With




        Next i
        sw.Close()
    End Sub


    Public Sub AddCustomer(ByVal lastName As String, ByVal firstName As String, ByVal customerNumber As Integer, _
                                   ByVal address As String, ByVal city As String, _
                                   ByVal state As String, ByVal zipCode As Integer, ByVal phoneNumber As Integer, _
                                   ByVal accountBalance As Integer, ByVal lastPayment As Date)
        If gCustomer Is Nothing Then
            ReDim gCustomer(0)
        Else
            ReDim Preserve gCustomer(gCustomer.Length)
        End If
        With gCustomer(gCustomer.Length - 1)
            .LastName = lastName
            .FirstName = firstName
            .LastName = lastName
            .CustomerNumber = customerNumber
            .Address = address
            .City = city
            .State = state
            .ZipCode = zipCode
        End With
    End Sub


End Module

I would also like some tips on designing my GUI because so far(my window I have for the save/open windown is a huge text box and in its filter properrty I have the text files code, would this form be all that it needs when the user saves and opens the file or is it more....

also for GUI on my first form that I have shown is a huge listbox in which the names are stored and just two buttons I have Exit and Get Employee Information
Im testing for input validation also so I know I would need a tryphase or try catch as statement to.

I also posted this on the msdn network but got no answer, so maybe I can get some help here....
 
Hi, Its a bit ambiguous the question.
Suggestion - Save the records as a dataset, save the data as an xml file.

here is a working example that shows saving and loading xml.
new project, windows forms.

Add these objects onto the form

VB.NET:
        Me.Button1 = New System.Windows.Forms.Button()
        Me.txt_ID1 = New System.Windows.Forms.TextBox()
        Me.txt_Nam1 = New System.Windows.Forms.TextBox()
        Me.txt_Age1 = New System.Windows.Forms.TextBox()
        Me.txt_ID2 = New System.Windows.Forms.TextBox()
        Me.txt_Nam2 = New System.Windows.Forms.TextBox()
        Me.txt_Age2 = New System.Windows.Forms.TextBox()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.TextBox22 = New System.Windows.Forms.TextBox()
        Me.TextBox23 = New System.Windows.Forms.TextBox()
        Me.TextBox24 = New System.Windows.Forms.TextBox()
        Me.TextBox14 = New System.Windows.Forms.TextBox()
        Me.TextBox13 = New System.Windows.Forms.TextBox()
        Me.TextBox12 = New System.Windows.Forms.TextBox()
        Me.Button2 = New System.Windows.Forms.Button()
        Me.dgv_Table = New System.Windows.Forms.DataGridView()
        Me.Label2 = New System.Windows.Forms.Label()



here is the code for windows form.

VB.NET:
Public Class Form1


    'A DataSet is conceptually a set of DataTables and other information about those tables. 
    'DataSet: This is a container for multiple DataTables. 
    'You can use it to create XML. 
    'It is a useful abstraction for simplifying programs.


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Button1.Enabled = False
        Button2.Enabled = True
        Dim MyDataSet As New DataSet


        MyDataSet.Tables.Add("t_Employe")
        With MyDataSet.Tables("t_Employe")
            .Columns.Add("c_ID")                 'XML <ITEm Name>
            .Columns.Add("c_Name")               'XML <ITEm Name>
            .Columns.Add("c_Age")                'XML <ITEm Name>


            .Rows.Add(txt_ID1.Text, txt_Nam1.Text, txt_Age1.Text)
            .Rows.Add(txt_ID2.Text, txt_Nam2.Text, txt_Age2.Text)
        End With


        MyDataSet.WriteXml(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) & "\temp.xml")
End Sub


    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Button1.Enabled = True
        Button2.Enabled = False


        Dim DS As New DataSet
        DS.ReadXml(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) & "\temp.xml")


        'Set dgv source = DS
        dgv_Table.DataSource = DS.Tables(0)


        Dim MyDictionary As Dictionary(Of String, String)
        MyDictionary = New Dictionary(Of String, String)


        For Each DR As DataRow In DS.Tables("t_Employe").Rows
            MyDictionary.Add(DR.Item("c_ID").ToString, DR.Item("c_Name").ToString.Trim)
        Next DR

        'check if c_ID is a 3 digit number
        Dim myRow As DataRow
        For Each myRow In DS.Tables("t_Employe").Rows
            If myRow.Item("c_ID").ToString.Length <> 3 Then
                Throw New Exception("Corrupted Distributor ID Length")
            End If
        Next


        Me.TextBox12.DataBindings.Add("Text", DS.Tables(0), "c_ID")
        Me.TextBox13.DataBindings.Add("Text", DS.Tables(0), "c_Name")
        Me.TextBox14.DataBindings.Add("Text", DS.Tables(0), "c_Age")

        Me.TextBox22.DataBindings.Add("Text", DS.Tables(0), "c_ID")
        Me.TextBox23.DataBindings.Add("Text", DS.Tables(0), "c_Name")
        Me.TextBox24.DataBindings.Add("Text", DS.Tables(0), "c_Age")

    End Sub

 End Class
 
Here is a screen shot

And loading it from the xml file.
 

Attachments

  • XML.PNG
    XML.PNG
    11.4 KB · Views: 37
  • XML 2.PNG
    XML 2.PNG
    14.6 KB · Views: 41
'I agree with Gopher 2011 a dataset or xml would be a better option.
'But i guess the point of the exercise is to learn about sequential file handling and file I/O.

'For this code to run add the following to a form:
'Create Data File
'Add File Path to form level variable
'TextBox = txtid, txtFname, txtLname
'Buttom = btnAdd, btnSave, btnSearch

Imports System.IO

Public Class Form1

Structure cCustomer
Dim id As Integer
Dim FirstName As String
Dim LastName As String
End Structure

Dim CustCollection As New Collection
Dim NewRecord As Boolean

Dim sDataFileName As String = "Put Data File Path Here"

Enum SearchBy
Id = 0
LastName = 1
End Enum

Private Function AddCustomer(ByVal ID As Integer, _
ByVal FirstName As String, _
ByVal Lastname As String) As Boolean

Dim NewCustomer As cCustomer

With NewCustomer
.id = ID
.FirstName = FirstName
.LastName = Lastname
End With

Try
CustCollection.Add(NewCustomer, NewCustomer.id.ToString)
NewRecord = True
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try

Me.Text = CustCollection.Count & " Records Loaded"
End Function

Private Function CustomerSearch(ByVal oCriteria As Object, ByVal SearchType As SearchBy) As cCustomer
For i As Integer = 1 To CustCollection.Count
Dim cCust As cCustomer = CustCollection(i)

Select Case SearchType
Case SearchBy.Id
If cCust.id = CType(oCriteria, Integer) Then
Return cCust : Exit For
End If
Case SearchBy.LastName
If cCust.LastName = CType(oCriteria, String) Then
Return cCust : Exit For
End If
End Select
Next

'return Nothing
End Function

Private Sub SaveData(ByVal sFileName As String)
Dim sStr As String = ""
Dim sw As New StreamWriter(sFileName, False)

sw.AutoFlush = True

For i As Integer = 1 To CustCollection.Count
Dim cCust As cCustomer = CustCollection(i)
sStr = cCust.id & ","
sStr += cCust.FirstName & ","
sStr += cCust.LastName & ","

sStr = sStr.Substring(0, sStr.LastIndexOf(","))

sw.WriteLine(sStr)
Next

sw.Close() : sw.Dispose()

End Sub

Private Sub LoadRecords(ByVal sFilname As String)
Dim sr As New StreamReader(sFilname)

Do While Not sr.EndOfStream
Dim tArr As Array = sr.ReadLine.Split(",")
Dim cCust As cCustomer

With cCust
.id = tArr(0)
.FirstName = tArr(1)
.LastName = tArr(2)
End With

CustCollection.Add(cCust, cCust.id.ToString)
Loop

sr.Dispose()
End Sub

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If NewRecord Then
If MsgBox("There are new records, save them?", _
MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Closing") = _
MsgBoxResult.Yes Then

SaveData(sDataFileName)
End If
End If
End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
LoadRecords(sDataFileName)
Me.Text = CustCollection.Count & " Records Loaded"
End Sub

Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Be sure to validate fisrt
If btnAdd.Text = "Clear" Then
txtID.Text = ""
txtFname.Text = ""
txtLname.Text = ""

btnAdd.Text = "Add"
txtID.Focus()
Else
If AddCustomer(txtID.Text, txtFname.Text, txtLname.Text) Then

txtID.Text = ""
txtFname.Text = ""
txtLname.Text = ""

btnAdd.Text = "Clear"

MsgBox("Record Added")
End If
End If

End Sub

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
If NewRecord Then
SaveData(sDataFileName)
NewRecord = False
MsgBox("Data Saved", MsgBoxStyle.Information)
End If
End Sub

Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim i As String = InputBox("Enter 1 for ID Search" & _
vbCrLf & _
"Enter 2 For Last Name Search", "Search Options")
Dim s As String = ""

If i = "1" Then
s = InputBox("Enter Customer ID", "ID Search")
If s <> "" Then
LoadSearch(CustomerSearch(s, SearchBy.Id))
Else
MsgBox("Invalid Entry", MsgBoxStyle.Exclamation)
Exit Sub
End If
ElseIf i = "2" Then
s = InputBox("Enter Customer Last Name", "Last Name Search")
If s <> "" Then
LoadSearch(CustomerSearch(s, SearchBy.LastName))
Else
MsgBox("Invalid Entry", MsgBoxStyle.Exclamation)
Exit Sub
End If
ElseIf i = "" Then
Exit Sub
Else
MsgBox("Invalid Entry", MsgBoxStyle.Exclamation)
Exit Sub
End If
End Sub

Private Sub LoadSearch(ByVal cCust As cCustomer)

With cCust
txtID.Text = .id
txtFname.Text = .FirstName
txtLname.Text = .LastName
End With


If cCust.FirstName = "" Then
MsgBox("Record not Found")
End If
End Sub
End Class
 

Latest posts

Back
Top