Link to home
Start Free TrialLog in
Avatar of MonteCristo33
MonteCristo33

asked on

VB2005 Read/Write to Random Access files - collect values from textboxes

Hi Experts,

I am migrating an old study system from VB5 to VB2005 Express. I have already received great help with this project on EE (Jaime, if you read this, this one's for you!).
I just got to grips with sequential file and streamers in VB2005, however I need to use the new equivalent of what used to be Random Access Files and need help with that.

The project is a car customiser form, with a range of controls on it. I have attached the current VB2005 code so you can see how the stuff works so far.
I'm trying to:
1. save individual files. The filename is based on the contents of my txtCarReg textbox
2. Loop through all my radio buttons and check boxes and print all relevant values to file
3. Open a previously saved file and populate all controls & textboxes on my form with the relevant values.

Here is the old VB5 code I'm trying to update, however I'm banging my head against the wall...
'saving individual records to a file based on contents of txtCarReg.text

Public ThisDir as String
ThisDir= Cur Dir + "\car quotes\"
Open (ThisDir + txtCarReg + ".cqu") for output as #1

'print contents of textboxes to file
Print #1, txtDate
Print #1, txtCustName
Print #1, txtCustName
Print #1, txtCustAddress
Print #1, "Address End"
Print #1, txtCarReg
Print #1, txtCarMake

'print contents of textboxes in option groups based on selection
For Counter = 0 to 2
if optWindow(counter)=true then  print #1, counter
next
For Counter = 0 to 2
if optSunroof(Counter) = true then Print #1, counter
next
For Counter = 0 to 2
if optPaintTYpe(Counter) = true then Print #1, counter
next
For Counter = 0 to 2
if optPaintColour(Counter) = true then Print #1, counter
next

'print contents of textboxes in the extras option group
For counter = 0 to 7
Print #1, chkExtra, (Counter)
next
Close #1

'opening the file and replacing all info in relevant textboxes
cdlFile.ShowOpen
Open cdlFile.filename for input as #1
Line Input #1, temp: txtDate=Temp
Line Input #1, temp: txtCustName=Temp
txtCustAddress=""
Temp=""
Do
      if Temp <> "" then
      txtCustAddress = txtCustAddress + Temp + vbcrlf
      Line Input #1, temp
Loop until Temp = "AddressEnd"

'populate the remaining textboxes
Input #1, temp: txtCarReg=temp
Input #1, temp: txtCarMake=temp
Input #1, tempOpt: optWindow(TempOpt).value=true
Input #1, tempOpt: optSunroof(TempOpt).value=true
Input #1, tempOpt: optPaintType(TempOpt).value=true
Input #1, tempOpt: optPaintColour(TempOpt).value=true
For Counter = 0 to 7
Input #1, TempOpt: chkExtra(counter) = TempOpt
Next

I know it's quite a lengthy project, but your time and help will be greatly appreciated
Thanks in anticipation
MC



Public Class Form1
    Public ThisDir As String
    Dim WindowsNoChange As Single = 0
    Dim WindowsAllElectric As Single = 450
    Dim WindowsFrontElectric As Single = 250
    Dim SunroofNoChange As Single = 0
    Dim SunroofManual As Single = 300
    Dim SunroofElectric As Single = 560
    Dim PaintNoChange As Single = 0
    Dim PaintPearl As Single = 600
    Dim PaintMetallic As Single = 720
    Dim MyDate As Date = Now
 
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ThisDir = CurDir() + "\car Quotes\"
 
        Me.txtCostAlloys.ReadOnly = True
        Me.txtCostFluffyDice.ReadOnly = True
        Me.txtCostHeatedSeats.ReadOnly = True
        Me.txtCostLeatherSeats.ReadOnly = True
        Me.txtCostSatNav.ReadOnly = True
        Me.txtCostSurroundSound.ReadOnly = True
        Me.txtCostTintedGlass.ReadOnly = True
        Me.txtCostTowBar.ReadOnly = True
        Me.txtCostWindows.ReadOnly = True
        Me.txtDate.ReadOnly = True
        Me.txtPaintCost.ReadOnly = True
        Me.txtQuote.ReadOnly = True
        Me.txtSunroofCost.ReadOnly = True
        txtDate.Text = Format(MyDate, "dd MMMM"", ""yyyy")
    End Sub
 
    Private Sub RadioButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdoNoChange.Click, rdoElectric.Click, rdoFrontElectric.Click
        Dim rad As RadioButton = CType(sender, RadioButton)
        Select Case rad.Name
            Case Me.rdoNoChange.Name
                Me.txtCostWindows.Text = WindowsNoChange
            Case Me.rdoElectric.Name
                Me.txtCostWindows.Text = WindowsAllElectric
            Case Me.rdoFrontElectric.Name
                Me.txtCostWindows.Text = WindowsFrontElectric
        End Select
        Call AddUp()
    End Sub
 
    Private Sub RadioButton2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdoSunroofNoChange.Click, rdoManual.Click, rdoRoofElectric.Click
        Dim rad2 As RadioButton = CType(sender, RadioButton)
        Select Case rad2.Name
            Case Me.rdoSunroofNoChange.Name
                Me.txtSunroofCost.Text = SunroofNoChange
            Case Me.rdoManual.Name
                Me.txtSunroofCost.Text = SunroofManual
            Case Me.rdoRoofElectric.Name
                Me.txtSunroofCost.Text = SunroofElectric
        End Select
        Call AddUp()
    End Sub
 
    Private Sub RadioButton3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdoPaintNoChange.Click, rdoPearl.Click, rdoMetallic.Click
        Dim rad3 As RadioButton = CType(sender, RadioButton)
        Select Case rad3.Name
            Case Me.rdoPaintNoChange.Name
                Me.txtPaintCost.Text = 0
                Me.rdoFierceRed.Enabled = False
                Me.rdoQuickSilver.Enabled = False
                Me.rdoSunsetBlue.Enabled = False
                Me.rdoInkBlack.Enabled = False
 
            Case Me.rdoPearl.Name
                Me.txtPaintCost.Text = 600
                Me.rdoFierceRed.Enabled = True
                Me.rdoQuickSilver.Enabled = False
                Me.rdoSunsetBlue.Enabled = True
                Me.rdoInkBlack.Enabled = True
                MsgBox("Pearl paint not available in Quick Silver", MsgBoxStyle.OkOnly, "Warning")
 
            Case Me.rdoMetallic.Name
                Me.txtPaintCost.Text = 720
                Me.rdoFierceRed.Enabled = True
                Me.rdoQuickSilver.Enabled = True
                Me.rdoSunsetBlue.Enabled = True
                Me.rdoInkBlack.Enabled = False
                MsgBox("Metallic paint not available in Ink Black", MsgBoxStyle.OkOnly, "Warning")
        End Select
        Call AddUp()
    End Sub
 
    Private Sub AddUp()
        Dim Quote As Single
        Quote = Val(txtCostWindows.Text) + Val(txtSunroofCost.Text) + Val(txtPaintCost.Text)
        For Each ctrl As Control In optExtras.Controls
            If TypeOf ctrl Is TextBox Then
                Quote = Quote + Val(CType(ctrl, TextBox).Text)
            End If
        Next
        txtQuote.Text = Format(Quote, "£0.00")
    End Sub
 
    Private Sub CheckBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.Click, CheckBox2.Click, CheckBox3.Click, CheckBox4.Click, _
    CheckBox5.Click, CheckBox6.Click, CheckBox7.Click, CheckBox8.Click
        Dim chk As CheckBox = CType(sender, CheckBox)
        Dim Index As String = chk.Name.Substring(8)
 
        Select Case Index
            Case "1"
                Me.txtCostAlloys.Text = IIf(chk.Checked, "280", "")
            Case "2"
                Me.txtCostSatNav.Text = IIf(chk.Checked, "120", "")
            Case "3"
                Me.txtCostLeatherSeats.Text = IIf(chk.Checked, "200", "")
            Case "4"
                Me.txtCostHeatedSeats.Text = IIf(chk.Checked, "100", "")
            Case "5"
                Me.txtCostSurroundSound.Text = IIf(chk.Checked, "250", "")
            Case "6"
                Me.txtCostTintedGlass.Text = IIf(chk.Checked, "240", "")
            Case "7"
                Me.txtCostTowBar.Text = IIf(chk.Checked, "180", "")
            Case "8"
                Me.txtCostFluffyDice.Text = IIf(chk.Checked, "10", "")
 
        End Select
        Call AddUp()
 
    End Sub
 
End Class

Open in new window

Avatar of Robberbaron (robr)
Robberbaron (robr)
Flag of Australia image

I consider the file you are working with to be a Sequential text file file.
You are using line input etc. Random Access files are usually binary and accessed using GET & PUT.
So the code you have for sequential & stream file should be sufficient.

Are you trying to import old data or is starting with new data files sufficient ?
Because it may be worth putting some structure into the text files.
eg put some header lines between groups of data. address, sunroof, paint
see http://www.builderau.com.au/program/windows/soa/Reading-and-writing-text-files-with-VB-NET/0,339024644,320267367,00.htm

You will have to replace the
Open (ThisDir + txtCarReg + ".cqu") for output as #1
Print #1, txtDate

with ....
Dim oFile as System.IO.File
Dim oWrite as System.IO.StreamWriter
oWrite = oFile.CreateText(C:\sample.txt)
oWrite.WriteLine(txtDate)
etc



replace ....

Open cdlFile.filename for input as #1
Input #1, temp
...with

Dim oFile as System.IO.File
Dim oRead as System.IO.StreamReader
oRead = oFile.OpenText(cdlFile.filename)
temp = oRead.ReadLine()
Avatar of MonteCristo33
MonteCristo33

ASKER

Hi RobberBaron,

Thanks for your post. What i'm really after is the Get.. Put sort of instructions that come with random files. I need to demonstrate that I can work with Random Files. I've already completed a project using System.IO streamers.
Perhaps I should cut my question into smaller, more manageable chunks, adding the algorithms I've come up with so far.
MC
SubProblem1: saving individual files. This form produces a quotation, adding up the price of various chosen options. I would like my system to save quotes as individual files, each file having its name taken from a textbox called txtCarReg (Car Registration).
Please bear in mind i have to use Random Files, and there's very little about those in the Microsoft Press books I'm using.

Would the attached code paired with a save event work? (I've indicated the bits I have no clue about as comments inside the code)

The individual Quote file should save all the contents of the textboxes + all the status of radio buttons and checkboxes

The idea is to then be able to subsequently open the saved file and populate all the controls on the form based on the information saved.

Hope this makes things a bit clearer.

Thanks

MC


SaveFileDialog1.Filter = "Text files(*.txt)|.txt
SaveFileDialog1.ShowDialog()
if SaveFileDilaog1.filename <> "" then
   FileOpen(1, 'how do I automatically name my file after the contents of my CarReg textbox?,OpenMode.random, 'no idea what comes next)
  FilePut (1, 'no idea how to grab all the relevant data from my controls on my form, do I need to build some kind of data structure?)
  File Close(1)
End Sub

Open in new window

"i have to use Random Files"

Is this a homework assignment?...why this requirement?

"do I need to build some kind of data structure?"

Yes...this is what Random Access Files are all about...reading and writing ENTIRE structures as a unit/record in the file.

The reason you're not finding much about this approach is that it is considered outdated.  It is actually possible to do this the same way as in the older versions of VB:
http://msdn2.microsoft.com/en-us/library/aa711474(VS.71).aspx
http://msdn2.microsoft.com/en-us/library/aa903289(VS.71).aspx
(there is a series of articles...follow the links...though the MSDN site is currently experiencing problems)

The "new" method of doing this would be to create a CLASS and read/write instances/collections of the class using either Binary or XML Serialization.
Hi IdleMind,

To answer your question, yes it is an assignment. The only stipulation is that I cannot use sequential files and I can't use a DB either. So I guess that leaves me with Random Files or Binary.

I need to learn the most up to date stuff anyway, and this prohect might be a good vehicle for me to understand binary serialization. However, please note that I had a look again at my MS Press books, and there's very little again about binary serialization. So I'm pretty much stranded here. My own knowledge is not enough for me to carry on and my books are very terse about the subject.
MC
Binary Serialization isn't used very often because it "breaks" when you make changes to the class.  Your more likely to see examples of XML Serialization.  Anything in your book on that?...
Idle Mind,

There is just a tiny section and it deals with ADO and linking to a DB, which I can't do here.
I just can't believe that what used to be straightforward before (see my original VB5 code above) has become nearly impossible and no two people agree how to do it.
All I'm trying to do is find a way to do in VB2005 what I could do so easliy in VB5. I don't care at that stage if it's sequential, random, binary or what...
Again, I need to store all textboxes values and radiobuttons / checkboxes status in an individual file so that all controls can be reset and populated accordingly next time the file is open to reflect the initial input 100%.
Your advice will be gladly received.
Thanks
MC
IdleMind,
I had a look at the links you included. I can see how I would need to build a structure to store the contents of my text boxes, however there is no example on how to store the state of a radiobutton or checkbox.
I'm losing thw will to live.. ;-)
I would really appreciate it if you could have a look at my original VB code and advise on the best course of action to port it to VB2005 so it fulfills its original purpose.
thanks
MC
ASKER CERTIFIED SOLUTION
Avatar of J1H1W1
J1H1W1

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi J1H1W1
Thanks for your input. Does the import feature work in the Express edition?

I'm getting an error message on the following line:
FileOpen(1, (ThisDir + txtCarReg.Text + ".cqu"), OpenMode.Output)
"NullReferenceException was unhandled"
"Object reference not set to an instance of an object."
"Use the NEW keyword?"

Do you understand it?

thanks

MC


Hi IdleMind,

Following your advice, I looked into xml serialization in my books and on the internet and built a small app to test it. It is actually quite clever. I'll probably put in a totally new post if I decide to go down that route.
But there's still a massive amount of work to be done.

MC
You should delete the first three lines.  Then the textboxes, radiobuttons and the OpenFileDialog should refer to names you used on your form.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Dear J1 and Idle Mind

Sorry I've been away for two days. Let me play with the code and I'll get back to you. I'll split the points between you when I'm done.
By the way, J1, I deleted those line, but I'm still getting the same error message.

Thanks for your time & support.

MC
Do you still have the textboxes, radiobuttons and the openfiledialog on the form and do they still have the same name as your original post?