PDA

Click to See Complete Forum and Search --> : How do you write code for a flat file database??


Shane Ottens
Mar 11th, 2000, 06:59 AM
I am just learning VB6 and have an exercise that I need to complete using a flat file database (I assume random access). I just don't know exactly where to start? Can any one give me some direction?

Serge
Mar 13th, 2000, 03:58 AM
Flat file is not a database. Well, you can kind of call it as a table.

Here is an exaple of using Random Access file.
Let's say you have an information of a Customer. Here are the fields that we're going to have:


CustomerID
LasName
FirstName
Address
City
State
Zip


First, we would create a User Defined Data Type to hold that customer information, then use that UDT to save the Customer record. For this purpose we would create 7 TextBoxes (txtCustomerID, txtLastName, txtFirstName, txtAddress, txtCity, txtState and txtZip). Also, let's add 2 buttons to your form (cmdSave and cmdNew):


Private Type udtCustomer
lngCustomerID As Long
strLasName As String * 15
strFirstName As String * 15
strAddress As String * 25
strCity As String * 15
strState As String * 2
strZip As String * 5
End Type

Private Sub cmdNew_Click()
Dim txt As Control

For Each txt In Me.Controls
If TypeOf txt Is TextBox Then
txt.Text = ""
End If
Next
End Sub


Private Sub cmdSave_Click()
Dim intFFN As Integer ' to hold next free file number
Dim strPath As String 'Path to the file
Dim tCustomer As udtCustomer 'variable to hold Customer info


strPath = "D:\Customer.txt"
intFFN = FreeFile

'First get the last CustomerID
'so we can generate next one
Open strPath For Random As intFFN Len = Len(tCustomer)
Get #intFFN, , tCustomer


'Get Customer Information
With tCustomer
'Increment ID
.lngCustomerID = tCustomer.lngCustomerID + 1
.strLasName = txtLastName
.strFirstName = txtFirstName
.strAddress = txtAddress
.strCity = txtCity
.strState = txtSate
.strZip = txtZip
End With

'Save the record
Put #intFFN, , tCustomer
'Show the new generated ID in the TextBox
txtCustomerID = tCustomer.lngCustomerID
'Close the file
Close #intFFN
End Sub


Private Sub Form_Load()
Dim strPath As String
Dim intFFN As Integer

intFFN = FreeFile
strPath = "D:\Customer.txt"
'If Customer.txt doesn't exit then create it.
If Dir(strPath) = "" Then
Open strPath For Output As intFFN
Close #intFFN
End If
End Sub


This is a small exaple of how to save the Customer info to the Random file. Check out MSDN as it has many examples of how to work with flat files.