Click here to Skip to main content
15,867,838 members
Articles / Programming Languages / Visual Basic
Article

VB.NET Solution for working with random files : Create, List, Update, and Delete

Rate me:
Please Sign up or sign in to vote.
3.75/5 (21 votes)
13 Jan 20043 min read 248.3K   2.1K   30   13
How to prepare an application for working with random files using VB.NET

Introduction

In this article, I will try to explain how to prepare an application for working with random files using VB.NET. Before starting, I want say that this application is just a sample for working with random files. Only the usage of random files are concentrated on, not the functionality of the program. If this is clear, we can start ;)

Implementation

In the first step, we are creating a new project and placing a TabControl on to the form. Then, create four tabs on the TabControl (select TabPages property and create these tabs) by names, “Create”, “Input”, “Output”, and “Search” as shown in Figure 1. below.

Figure 1. TabControl on the form

In the second step, use TextBox, Label, Button, and ListBox components and form the tab pages as shown below.

Figure 2. Tab page “Create”

Figure 3. Tab page “Input”

Figure 4. Tab page “Output”

Figure 5. Tab page “Search”

Now, the form will look like the form in Figure 6. below. Note that the “Exit” button is placed on the form to just terminate the application.

Figure 6. Application form

In the third step, we are starting to write source code for our application. First of all, let’s define a global variable, record type and write a function to find the last record number of the random file.

VB
'Create a global variable. This variable will keep the 
'position of related record.
Dim Position As Integer

'Create a record type. The name of the record 
'type is given as "Person".
Structure Person
   Dim ID As Integer
   Dim Name As String
   Dim Surname As String
End Structure

'This is the function that we are using to find a last 
'record’s number in the random file.
Private Function FindLastRecordNo() As Integer
    Dim Temp As Person, FileNumber As Integer
    
    'Get the available file number.    
    FileNumber = FreeFile()
    
    'Open the file by using the FileOpen statement 
    'in a random mode with       
    'only read access. The name of the file 
    'will be same as the text in the  
    'TextBox1 (Textbox1 is on the "Create" tab page). 
    'Len(Temp) function is use 
    'to determine the size of record in bytes. 
    FileOpen(FileNumber, TextBox1.Text, OpenMode.Random,  _
      OpenAccess.Read, , Len(Temp))
    
    FindLastRecordNo = 1
    
    'EOF() function is using to detect the end of file.
    Do While Not EOF(FileNumber)
        'FileGet() function is using to get a record from random file.
        FileGet(FileNumber, Temp, )
        FindLastRecordNo = FindLastRecordNo + 1
    Loop

    'Close the file.
    FileClose(FileNumber)
End Function

Here are the event procedures and explanations of important statements. Note that “...” is used, instead of writing arguments, in each procedure title because of easy readability. This is only for Exit button to terminate the application.

VB
Private Sub Button1_Click(…) Handles Button1.Click
        End
End Sub
This event procedure is for Create button on the “Create” tab page.
VB
Private Sub Button2_Click(…) Handles Button2.Click
        Dim RecLength As Long, Employee As Person

        'Get the next available file number.
        FileNum = FreeFile()
        
        'Open the new random file with the FileOpen statement.
        FileOpen(FileNum, TextBox1.Text, _
          OpenMode.Random, , , Len(Employee))
        
  'Close the file.
  FileClose(FileNum)
End Sub
When the user clicks Insert button on the “Input” tab page, this procedure will run and save the new record at the end of the random file.
VB
Private Sub Button3_Click(…) Handles Button3.Click
        Dim Employee As Person, LastRecord As Integer
        
        'Find the last record number of random file. FindLastRecordNo() 
        'function, which is shown above, is called.
        LastRecord = FindLastRecordNo() 

        FileNum = FreeFile()
        FileOpen(FileNum, TextBox1.Text, OpenMode.Random, , , Len(Employee))
        Employee.ID = Val(TextBox2.Text)
        Employee.Name = TextBox3.Text
        Employee.Surname = TextBox4.Text

        'Put the Employee record into the random file as a last record.
        FilePut(FileNum, Employee, LastRecord)

        FileClose(FileNum)
End Sub
Read all records in the random file and put these records into the Listbox one by one. This is the procedure for Read button on the “Output” tab page.
VB
Private Sub Button4_Click(…) Handles Button4.Click
  Dim Employee As Person, Count As Integer, Temp As String
  FileNum = FreeFile()
  FileOpen(FileNum, TextBox1.Text, OpenMode.Random, , , Len(Employee))
  Count = 1
  ListBox1.Items.Clear()
  Do While Not EOF(FileNum)
      'Read the record on the position Count.
      FileGet(FileNum, Employee, Count)

      'str() function is used to convert integer to string.
      Temp = Str(Employee.ID) + "  " + Employee.Name + _
        "  " + Employee.Surname
      
      'Add the string into Listbox.
      ListBox1.Items.Add(Temp)
      Count = Count + 1
  Loop
  FileClose(FileNum)
End Sub
This is the Find button on the “Search” tab page. It is searching all records in the random file until it finds Employee ID in the record is equal to the ID in the TextBox5 (Textbox5 is assigned to Employee Id on the “Search” tab page.)
VB
Private Sub Button6_Click(…) Handles Button6.Click
        Dim Employee As Person
        FileNum = FreeFile()
        FileOpen(FileNum, TextBox1.Text, _
          OpenMode.Random, , , Len(Employee))
        Do While Not EOF(FileNum)
            FileGet(FileNum, Employee, )
            If Employee.ID = Val(TextBox5.Text) Then
                'Keep the current position of record 
                'in "Position" variable to 
                'use in further use such as update or delete operations.
                Position = Loc(FileNum) 
    
                'Change enable status for some Textboxes.
                TextBox5.Enabled = False
                TextBox6.Enabled = True
                TextBox7.Enabled = True
                Button5.Enabled = True
                Button6.Enabled = False
                Button7.Enabled = True
            
               'Show the Employee name and surname in the related Textboxes.
                TextBox6.Text = Employee.Name
                TextBox7.Text = Employee.Surname
                Exit Do
            End If
        Loop
        FileClose(FileNum)
End Sub
This procedure is for Update button (“Search” tab page) and is to update the record. We know the position of found record from Find procedure and we will use this position to overwrite the information of Employee on this record.
VB
Private Sub Button5_Click(…) Handles Button5.Click
        Dim Employee As Person
        FileNum = FreeFile()
        FileOpen(FileNum, TextBox1.Text, _
          OpenMode.Random, , , Len(Employee))
      
        'Seek() function is used to move the pointer 
        'to any position of random file.
        Seek(FileNum, Position)

        'Update the information of an Employee.
        Employee.ID = Val(TextBox5.Text)
        Employee.Name = TextBox6.Text
        Employee.Surname = TextBox7.Text
        FilePut(FileNum, Employee, )
        FileClose(FileNum)

        'Change the enable status of some Textboxes and 
        'clear the texts in these Textboxes.
        TextBox5.Enabled = True
        TextBox6.Enabled = False
        TextBox7.Enabled = False
        Button5.Enabled = False
        Button6.Enabled = True
        Button7.Enabled = False
        TextBox5.Text = ""
        TextBox6.Text = ""
        TextBox7.Text = ""
End Sub
This procedure is for Delete button (“Search” tab page) and is to delete the record. In this procedure, we are opening our random file and one temporary file. Then copying all records except the record, which its position number kept by Position variable, into the temporary file. After that, we delete our random file and rename the temporary file by giving the same name as deleted random file. This name is found in the Textbox1 (“Create” tab page.)
VB
Private Sub Button7_Click(…) Handles Button7.Click
  Dim Employee As Person, FileNum1, FileNum2 As Integer
  FileNum1 = FreeFile()
  FileOpen(FileNum1, TextBox1.Text, OpenMode.Random, _
     OpenAccess.Read, , Len(Employee))
  FileNum2 = FreeFile()
  
  'This is for temporary random file.
  FileOpen(FileNum2, "abcdefg.tnt", OpenMode.Random, _
     OpenAccess.Write, , Len(Employee))

  Do While Not EOF(FileNum1)
      'We used "Position-1" because we do not want to 
      'copy the record, which its 
      'record position is equal to Position variable, 
      'to the temporary file. 
      'When the pointer comes to the previous record, 
      'we want it to read the 
      'record which its position is equal to Position 
      'variable and do not write 
      'this into temporary file (Else statement). 
      'For example, if we want to 
      'delete third record (Position=3), when the
      'pointer comes to the record 2 
      '(loc(FileNum1)=Position-1 condition is valid), 
      'it will make only 
      'FileGet(). This means that it will not 
      'write the record 3 to temporary 
      'file. Note that; FileGet() function reads 
      'record 3 when pointer is on record 2. 
      If (Loc(FileNum1) <> Position - 1) Then
         FileGet(FileNum1, Employee, )
         FilePut(FileNum2, Employee, )
      Else
         FileGet(FileNum1, Employee, )
      End If
  Loop

  FileClose(FileNum1)
  FileClose(FileNum2)

  'Delete the random file.
  Kill(TextBox1.Text)

  'Rename the temporary file by giving the same 
  'name as deleted random file.
  Rename("abcdefg.tnt", TextBox1.Text)

  'Change the enable status of some Textboxes 
  'and clear the texts in these 
  'Textboxes.
  TextBox5.Enabled = True
  TextBox6.Enabled = False
  TextBox7.Enabled = False
  Button5.Enabled = False
  Button6.Enabled = True
  Button7.Enabled = False
  TextBox5.Text = ""
  TextBox6.Text = ""
  TextBox7.Text = ""
End Sub

Have a nice day!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Instructor / Trainer
Turkey Turkey
Asst. Prof. in Eastern Mediterranean University.

Comments and Discussions

 
Questioni m new in this fild so i need help :( plz help me , plz plz :'( Pin
jacksudhir24-Aug-12 7:39
jacksudhir24-Aug-12 7:39 
AnswerRe: i m new in this fild so i need help :( plz help me , plz plz :'( Pin
jacksudhir24-Aug-12 7:40
jacksudhir24-Aug-12 7:40 
GeneralThe code in the article should be updated... Pin
Ray Cassick17-May-08 6:34
Ray Cassick17-May-08 6:34 
GeneralRe: The code in the article should be updated... Pin
Blue stone20-Oct-08 0:15
Blue stone20-Oct-08 0:15 
GeneralRe: The code in the article should be updated... Pin
Ray Cassick20-Oct-08 2:01
Ray Cassick20-Oct-08 2:01 
GeneralRandom File Access Wraper Pin
Polymorpher10-May-08 8:52
Polymorpher10-May-08 8:52 
Generalabout globle variable Pin
bapu28898-Apr-07 3:07
bapu28898-Apr-07 3:07 
QuestionCan not use array in structure? Pin
Anonymous19-Sep-05 21:13
Anonymous19-Sep-05 21:13 
Generalinclude array in structure Pin
Anonymous19-Sep-05 21:11
Anonymous19-Sep-05 21:11 
Question&quot;Random&quot; files? Pin
dog_spawn14-Jan-04 5:32
dog_spawn14-Jan-04 5:32 
Random access...? Can you clarify that please.
AnswerRe: &quot;Random&quot; files? Pin
Michael Russell14-Jan-04 9:46
Michael Russell14-Jan-04 9:46 
GeneralRe: &quot;Random&quot; files? Pin
dog_spawn14-Jan-04 14:10
dog_spawn14-Jan-04 14:10 
GeneralRe: &quot;Random&quot; files? Pin
Fluid Dynamics Software18-Oct-07 13:14
Fluid Dynamics Software18-Oct-07 13:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.