Data files and databases
Jan 01, 2016
Data files and databases
• Need a control to browse to a file• Standard controls for drive folder and list not
much use• The CommonDialogs control offers
– drive folder file browse to select file– print– font select– colour select
• But you need to add it in..
Using the Common Dialog Control
Private Sub Command1_Click()CommonDialog1.ShowOpenMsgBox ("You selected " & CommonDialog1.FileName).. code to process FileNameEnd Sub
File open exercise
Program to browse and display graphics filesUse a common dialog control to select graphics filesSet the filter of the dialog to something like: Image files | *.bmp; *.jpg; *.jpeg | All files | *.*Display the selected image in a Picture control (see graphics)
VB data file ideas 2 modes –
• sequential (work through file start to end - character (external format))
• random (can move back and forth through file, binary (internal format) )
Sequential – write # and input#
Open "c:\walter\vb\filing\test1.dat" For Output As #1Write #1, 1, 2, 3.1, "Test1", "Test2"Close #1
Open "c:\walter\vb\filing\test1.dat" For Input As #1Input #1, x, y, z, a, bClose #1
Sequential – Print # and Line Input#Open "c:\walter\vb\filing\test1.dat" For Output As #1Print #1, 1, 2, "Test1"Close #1
Open "c:\walter\vb\filing\test1.dat" For Input As #1Line Input #1, xClose #1
MsgBox (x)
Exercise – sequential filing
1. Fill an array with 100 random integers2. Save them into a file ( write# )3. Read file back ( input# ) into a second array4. Check arrays have same content
Random
• Data in file as records• Must define size of record (fixed length good)• Can then seek to nth record • And read or write it
User-defined type (record)Private Type myRecordpayroll As Integerdepartment As Integername As String * 14End Type
fixed length string
length of record = 2 + 2 + 14 = 18 bytes
Writing to random access file
Dim emp As myRecordemp.payroll = 23emp.department = 3emp.name = "Fred"Open "c:\walter\vb\filing\test.dat" For Random As #1 Len = 18Put #1, 1, empemp.payroll = 17emp.department = 6emp.name = "John"Put #1, 2, empPut #1, 3, empClose #1
result on next slide
record position 1
Random file contents
record 1 record 2 record 3
2 bytes = integer = 23
2 bytes = 1 integer = 3
string padded with spaces to length 14
Reading Random File
Dim emp As myRecordOpen "c:\walter\vb\filing\test.dat" For Random As #1 Len = 18Get #1, 2, empClose #1MsgBox (emp.payroll & " " & emp.department & " " &_ emp.name)
read second record
Binary = random with record size 1Dim b As ByteOpen "c:\walter\vb\filing\test.dat" For Binary As #1For bytePosition = 1 To 10 Get #1, bytePosition, b Debug.Print bNextClose #1
Exercise – data file
• Using binary mode, write the characters A to Z into a file (ASCII 65 on)
• Then read them back in reverse ie byte position 26 first
• Debug.print them out
Working with a database – the hard way
Private Sub Command1_Click()Data1.Recordset.DeleteData1.RefreshEnd Sub