Solved

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

Posted on 2007-12-01
16
944 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
  • 8
  • 3
  • 3
  • +1
16 Comments
 
LVL 32

Expert Comment

by:Robberbaron (robr)
Comment Utility
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)
Comment Utility
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
Comment Utility
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
 

Author Comment

by:MonteCristo33
Comment Utility
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 85

Expert Comment

by:Mike Tomlinson
Comment Utility
"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
Comment Utility
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 85

Expert Comment

by:Mike Tomlinson
Comment Utility
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
Comment Utility
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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:MonteCristo33
Comment Utility
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 250 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 250 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

743 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now