?
Solved

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

Posted on 2007-12-01
16
Medium Priority
?
1,004 Views
Last Modified: 2013-12-25
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

0
Comment
Question by:MonteCristo33
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 3
  • 3
  • +1
16 Comments
 
LVL 32

Expert Comment

by:Robberbaron (robr)
ID: 20390610
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
0
 
LVL 32

Expert Comment

by:Robberbaron (robr)
ID: 20390630
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()
0
 

Author Comment

by:MonteCristo33
ID: 20391832
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
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:MonteCristo33
ID: 20391946
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

0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 20392044
"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.
0
 

Author Comment

by:MonteCristo33
ID: 20392114
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
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 20392138
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?...
0
 

Author Comment

by:MonteCristo33
ID: 20392226
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
0
 

Author Comment

by:MonteCristo33
ID: 20392331
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
0
 
LVL 4

Accepted Solution

by:
J1H1W1 earned 750 total points
ID: 20392639
This is the way VB2005 upgrades your original code:

	Dim txtCarReg, txtDate, txtCustName, txtCustAddress, txtCarMake As TextBox
	Dim optWindow(2), optSunroof(2), optPaintType(2), optPaintColour(2), chkExtra(7) As RadioButton
	Dim cdlFile As OpenFileDialog
	Sub SaveData()
		Dim ThisDir As String = CurDir() + "\car quotes\"
		FileOpen(1, (ThisDir + txtCarReg.Text + ".cqu"), OpenMode.Output)
		'print contents of textboxes to file
		PrintLine(1, txtDate.Text)
		PrintLine(1, txtCustName.Text)
		PrintLine(1, txtCustName.Text)
		PrintLine(1, txtCustAddress.Text)
		PrintLine(1, "Address End")
		PrintLine(1, txtCarReg.Text)
		PrintLine(1, txtCarMake.Text)
		Dim counter As Integer
		'print contents of textboxes in option groups based on selection
		For counter = 0 To 2
			If optWindow(counter).Checked = True Then PrintLine(1, counter)
		Next
		For counter = 0 To 2
			If optSunroof(counter).Checked = True Then PrintLine(1, counter)
		Next
		For counter = 0 To 2
			If optPaintType(counter).Checked = True Then PrintLine(1, counter)
		Next
		For counter = 0 To 2
			If optPaintColour(counter).Checked = True Then PrintLine(1, counter)
		Next
		'print contents of textboxes in the extras option group
		For counter = 0 To 7
			PrintLine(1, chkExtra(counter).Checked)
		Next
		FileClose(1)
	End Sub
	Sub LoadData()
		'opening the file and replacing all info in relevant textboxes
		cdlFile.ShowDialog()
		FileOpen(1, cdlFile.FileName, OpenMode.Input)
		txtCustName.Text = LineInput(1)
		txtCustAddress.Text = ""
		Dim temp As String
		Do
			txtCustAddress.Text += temp
			temp = LineInput(1)
			If temp = "AddressEnd" Then Exit Do
		Loop
		'populate the remaining textboxes
		txtCarReg.Text = LineInput(1)
		txtCarMake.Text = LineInput(1)
		Dim TempOpt As Integer
		Input(1, TempOpt)
		optWindow(TempOpt).Checked = True
		Input(1, TempOpt)
		optSunroof(TempOpt).Checked = True
		Input(1, TempOpt)
		optPaintType(TempOpt).Checked = True
		Input(1, TempOpt)
		optPaintColour(TempOpt).Checked = True
		For counter As Integer = 0 To 7
			Input(1, chkExtra(counter).Checked)
		Next
	End Sub

Open in new window

0
 

Author Comment

by:MonteCristo33
ID: 20398318
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


0
 

Author Comment

by:MonteCristo33
ID: 20398400
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
0
 
LVL 4

Expert Comment

by:J1H1W1
ID: 20398447
You should delete the first three lines.  Then the textboxes, radiobuttons and the OpenFileDialog should refer to names you used on your form.
0
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 750 total points
ID: 20399673
Here is a contrived example of using a Random access file to store the data from some TextBoxes/RadioButtons:
(though in your actual problem you are only storing ONE record in the file so it's kinda pointless to use Random Access!)

    Public Structure MyData
        <VBFixedString(30)> Public Text1 As String
        <VBFixedString(30)> Public Text2 As String
        Public Option1a As Boolean
        Public Option1b As Boolean
        Public Option1c As Boolean
        Public Option2a As Boolean
        Public Option2b As Boolean
        Public Option2c As Boolean
    End Structure

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim md As New MyData
        md.Text1 = TextBox2.Text
        md.Text2 = TextBox3.Text
        md.Option1a = RadioButton1.Checked
        md.Option1b = RadioButton2.Checked
        md.Option1c = RadioButton3.Checked
        md.Option2a = RadioButton4.Checked
        md.Option2b = RadioButton5.Checked
        md.Option2c = RadioButton6.Checked
        FileOpen(1, TextBox1.Text, OpenMode.Random, OpenAccess.Write, OpenShare.Shared, Len(md))
        FilePut(1, md)
        FileClose(1)
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim md As New MyData
        FileOpen(1, TextBox1.Text, OpenMode.Binary, OpenAccess.Read, OpenShare.Shared, Len(md))
        FileGet(1, md)
        FileClose(1)
        TextBox2.Text = md.Text1
        TextBox3.Text = md.Text2
        RadioButton1.Checked = md.Option1a
        RadioButton2.Checked = md.Option1b
        RadioButton3.Checked = md.Option1c
        RadioButton4.Checked = md.Option2a
        RadioButton5.Checked = md.Option2b
        RadioButton6.Checked = md.Option2c
    End Sub
0
 

Author Comment

by:MonteCristo33
ID: 20422184
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
0
 
LVL 4

Expert Comment

by:J1H1W1
ID: 20422495
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?
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
This article describes how to use a set of graphical playing cards to create a Draw Poker game in Excel or VB6.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question