QReferate - referate pentru educatia ta.
Cercetarile noastre - sursa ta de inspiratie! Te ajutam gratuit, documente cu imagini si grafice. Fiecare document sau comentariu il poti downloada rapid si il poti folosi pentru temele tale de acasa.



AdministratieAlimentatieArta culturaAsistenta socialaAstronomie
BiologieChimieComunicareConstructiiCosmetica
DesenDiverseDreptEconomieEngleza
FilozofieFizicaFrancezaGeografieGermana
InformaticaIstorieLatinaManagementMarketing
MatematicaMecanicaMedicinaPedagogiePsihologie
RomanaStiinte politiceTransporturiTurism
Esti aici: Qreferat » Documente informatica

Interactionarea cu datele dintr-un fisier text ASCII



Interactionarea cu datele dintr-un fisier text ASCII

Datele necesare aplicatiei nu sunt intotdeauna stocate intr-o baza de date relationala. Ele pot fi stocate in campuri de lungime fixa sau delimitate intr-un fisier text ASCII. Spre exemplu, sursa de date a aplicatiei poate fi formata din datele descarcate intr-un fisier text dintr-un calculator mainframe, un fisier convertit dintr-un format de baza de date nesuportat sau dintr-un fisier de date "ad-hoc" creat cu un editor de texte.

Prin crearea unei clase data-aware si folosind Microsoft ActiveX Data Objects (ADO), puteti utiliza Visual Basic pentru a crea aplicatii care interactioneaza cu datele dintr-un fisier text ASCII. Aplicatia va putea citi datele dintr-un fisier text, actualiza campurile, adauga noi articole si scrie datele inapoi in fisierul text, ca si cum datele ar fi inregistrate intr-o baza de date relationala.

Crearea unei clase data-aware care sa citeasca articolele dintr-un fisier text cu delimitatori

Prin crearea unei clase data-aware, puteti citi datele dintr-un fisier text delimitat intr-un set de articole ADO si sa folositi facilitatile ADO pentru manipularea datelor. Puteti apoi utiliza clasa ca sursa de date in aplicatia dvs., legand controalele de pe formular la campurile din setul de articole.



Pentru a crea o clasa data-aware care sa citeasca datele dintr-un fisier text delimitat trebuie sa executati urmatoarele operatii:

Crearea clasei care va actiona ca sursa de date.

Adaugarea codui pentru citirea datelor din fisierul text intr-un set de articole ADO.

Setarea sursei de date a clasei.

Crearea unei clase care actioneaza ca o sursa de date

Puteti crea o clasa care sa actioneze ca o sursa de date in proiectul dvs. inserand un modul al clasei si precizand functionarea sursei de date a acestuia. In primul rand, inserati un modul al clasei in proiect selectand comanda Add Class Module din meniul Project. Apoi setati proprietatile Name si DataSourceBehavior ale clasei.

Spre exemplu, pentru a crea clasa CustomerDataSource care sa actioneze ca o sursa de date, setati proprietatile astfel:

Proprietate

Valoare

Name

CustomerDataSource

DataSourceBehavior

vbDataSource

Adaugarea codului pentru citirea datelor din fisierul text intr-un set de articole ADO

Prin citirea datelor dintr-un fisier text intr-un set de articole ADO, puteti utiliza facilitatile din ADO pentru prelucrarea datelor. In primul rand, adaugati o referinta la biblioteca obiectului ADO prin selectarea comenzii References din meniul Project si apoi selectati optiunea Microsoft ActiveX Data Objects 2.0 Library din caseta de dialog References.

In continuare, in sectiunea Declarations a modulului clasei declarati o variabila a obiectului Recordset. Spre exemplu, pentru a declara o variabila a obiectului Recordset pentru lucrul cu articolele clientilor din fisierul Customers.txt, adaugati urmatoarea declaratie in sectiunea Declarations a modulului clasei:

Public rsCustomers As ADODB.Recordset

Declarand variabila ca o variabila publica, puteti utiliza metodele intrinseci ale obiectului Recordset in aplicatiile care folosesc calsa data-aware.

In sfarsit, adaugati cod procedurii evenimentului Class_Initialize a clasei pentru a citi datele din fisierul text. Spre exemplu, adaugati urmatorul cod in procedura evenimentului Class_Initialize a clasei CustomerDataSource pentru a citi datele din fisierul Customers.txt intr-un set de articole:

Private Sub Class_Initialize()

Dim fld As ADODB.Field

Dim strRow As String

Dim strField As String

Dim intPos As Integer

Set rsCustomers = New ADODB.Recordset

With rsCustomers

' Seteaza CustomerID drept cheie primara.

.Fields.Append 'CustomerID', adChar, 5, adFldRowID

.Fields.Append 'CompanyName', adChar, 40, adFldUpdatable

.Fields.Append 'ContactName', adChar, 30, adFldUpdatable

.Fields.Append 'ContactTitle', adChar, 30, adFldUpdatable

.Fields.Append 'Address', adChar, 60, adFldUpdatable

.Fields.Append 'City', adChar, 15, adFldUpdatable

.Fields.Append 'Region', adChar, 15, adFldMayBeNull

.Fields.Append 'PostalCode', adChar, 10, adFldMayBeNull

.Fields.Append 'Country', adChar, 15, adFldUpdatable

.Fields.Append 'Phone', adChar, 24, adFldUpdatable

.Fields.Append 'Fax', adChar, 24, adFldMayBeNull

' Se foloseste cursorul Keyset pentru a permite actualizarea.

.CursorType = adOpenKeyset

.LockType = adLockOptimistic

.Open

End With

Open 'Customers.txt' For Input As #1

Do Until EOF(1)

Line Input #1, strRow

With rsCustomers

.AddNew

For Each fld In .Fields

' Daca s-a gasit un delimitator tab, atunci campul text

' este la stanga delimitatorului.

If InStr(strRow, Chr(9)) <> 0 Then

' Se muta pozitia pe delimitatorul tab.

intPos = InStr(strRow, Chr(9))

' Atribuirea campului text variabilei strField.

strField = Left(strRow, intPos - 1)

Else

' Daca nu este gasit un delimitator tab, atunci

' campul este ultimul in linie.

strField = strRow

End If

' Se elimina ghilimelele.

If Left(strField, 1) = Chr(34) Then

strField = Left(strField, Len(strField) - 1)

strField = Right(strField, Len(strField) - 1)

End If

fld.Value = strField

' Se elimina valoarea campului text din linie.

strRow = Right(strRow, Len(strRow) - intPos)

intPos = 0

Next

.Update

.MoveFirst

End With

Loop

Close

End Sub

Setarea sursei de date a clasei

Atunci cand specificati o clasa ca sursa de date prin setarea pe valoarea vbDataSource a proprietatii DataSourceBehavior a acesteia, Visual Basic adauga automat un eveniment GetDataMember la clasa. Procedura eveniment Class_GetDataMember este locul unde sursa de date a clasei prin atribuirea ei la obiectul Data a clasei.

Spre exemplu, pentru a seta setul de articoel rsCustomers ca sursa de date pentru clasa CustomerDataSource, in procedura eveniment Class_GetDataMember se adauga codul urmator:

Private Sub Class_GetDataMember(DataMember As String, Data As Object)

Set Data = rsCustomers

End Sub

Crearea unui formular pentru vizualizarea si actualizarea datelor dintr-o clasa data-aware

Dupa ce ati creat o clasa care sa actioneze ca o sursa de date, puteti realiza foarte usor aplicatii care sa va permita vizualizarea si actualizarea articolelor din sursa de date. Puteti folosi ActiveX Data Objects (ADO) si obiectul BindingsCollection pentru a lega sursa de date de controalele continute de formular si puteti adauga butoane pentru navigarea printre articole.

Pentru a crea un formular care sa va permita vizualizarea si actualizarea datelor dintr-o clasa data-aware trebuie sa executati urmatoarele operatii:

Adaugarea pe formular a controalelor TextBox si Label necesare.

Adaugarea codului pentru legarea casetelor de text de sursa de date.

Adaugarea butoanelor de comanda pentru navigarea printre articole.

Adaugarea casetelor de text si a etichetelor pe formular

Primul pas in vizualizarea si actualizarea datelor dintr-o clasa data-aware este crearea unei interfete pentru a interactiona cu articolele din sursa de date. Cea mai usoara cale de a crea interfata este deschiderea unui nou proiect Standard EXE si adaugarea casetelor de text si a etichetelor pe formular.

Spre exemplu, puteti crea o interfata pentru vizualizarea informatiei de adresa a clientului din fisierul Customers.txt. Mai intai, adaugati eticheta 'Customer ID:' pe formular si apoi adaugati o caseta de text langa eticheta si setati proprietatea Name a acesteia pe txtCustomerID. Repetati procesul pentru controalele CompanyName, Address, City, Region, PostalCode si Country.

Adaugarea codului pentru legarea la sursa de date a casetelor de text

Using a data-aware class, ActiveX Data Objects (ADO), and the BindingCollection object, you can bind controls to a data source when the page loads. You can then edit the data and add code to navigate through the records. For example, you can use an instance of your data-aware class and the BindingCollection object to bind the text box controls on your form to fields from the Customers.txt file.

First, add a reference to the BindingCollection object's type library to your project. To add the reference, select References on the Project menu, then select Microsoft Data Binding Collection in the References dialog box.

Then declare variables for the data-aware class and a BindingCollection object in your form's Declarations section:

Private objDataSource As CustomerDataSource

Private colBind As BindingCollection

To bind the text box controls to fields from the Customers.txt file when the form loads, add code to the form's Load event procedure. An instance of the CustomerDataSource class reads records from the text file into an ADO recordset, and the BindingCollection object binds the text box controls to fields in the recordset:

Private Sub Form_Load()

Set objDataSource = New CustomerDataSource

Set colBind = New BindingCollection

Set colBind.DataSource = objDataSource

colBind.Add txtCustomerID, 'Text', 'CustomerID'

colBind.Add txtCompanyName, 'Text', 'CompanyName'

colBind.Add txtAddress, 'Text', 'Address'

colBind.Add txtCity, 'Text', 'City'

colBind.Add txtRegion, 'Text', 'Region'

colBind.Add txtPostalCode, 'Text', 'PostalCode'

colBind.Add txtCountry, 'Text', 'Country'

End Sub

Add Command Button Controls to Navigate through Records

By binding controls on your form to a public recordset in your data-aware class, you can easily create Next and Previous buttons that let you navigate through records. Each command button requires a single line of code.

For example, to create a Next button for the form that displays customer records, add a command button to the form and change its Caption and Name properties to Next. Then add the following line to the command button's Next_Click event procedure:

objDataSource.rsCustomers.MoveNext

The code uses the MoveNext method of the rsCustomers recordset that serves as the data source for the form's controls. It refers to the recordset as a property of the object variable that represents an instance of the CustomerDataSource class.

Similarly, you can create Previous, First, and Last buttons by adding command buttons to the form and changing their Caption and Name properties to Previous, First, and Last, respectively. Then add code to the Click event procedure for each command button that invokes the MovePrevious, MoveFirst, and MoveLast methods.

When you run the form, Visual Basic lets you view and update records from the Customers.txt file and lets you navigate through the recordset.

Modifying the Form to Let You Add New Records

In addition to viewing and updating existing records, you may want to add new records to your data source. You can modify your form so that it can serve as a data entry form by creating command buttons that use ActiveX Data Objects (ADO) and the BindingsCollection object to clear the display of data, manage the data binding of controls, and add a new record to the underlying recordset.

This topic shows how to modify the form you created in the previous topic so that it also serves as a data entry form for adding new customer records.

To modify the form to let you add new records

Create command buttons for allowing data entry, adding new customer records, and returning to viewing data.

Add code to enable data entry.

Add code to enable saving the data you enter as a new record.

Add code to enable returning the form to viewing data.

Note   This topic is part of a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. It begins with the topic Interacting with Data in an ASCII Text File.

Create Command Buttons for Allowing Data Entry, Adding New Customer Records, and Returning to Viewing Data

The first step in modifying the form is to create the interface for the tasks that you want to accomplish. For example, to allow data entry on the customer address form you created in the previous topic, you could add the following:

A DataEntry command button to clear the existing data displayed on the form and disable data binding.

An AddCustomer command button to add new data entered on the form as a new record in the underlying recordset.

A ViewData command button to re-enable data binding, returning the form to its original state.

First, add a command button to the form and change its Caption and Name properties to DataEntry. Add a second command button to the form and change its Caption and Name properties to AddCustomer. Then add a third command button to the form and change its Caption and Name properties to ViewData.

Because the AddCustomer and ViewData command buttons should only be displayed when the form is being used for data entry, set the Visible property for these controls to False.

Add Code to Enable Data Entry

You can make a data-bound form also serve as a data entry form by disabling data binding and clearing the existing data displayed on the form. You may also want to show hidden command button controls that apply only to adding new records, and hide command button controls that apply only to viewing existing records.

For example, to enable the DataEntry command button on the customer address form, add the following code to the DataEntry_Click event procedure:

Private Sub DataEntry_Click()

' Disable data binding.

Set colBind = Nothing

' Clear the text box controls.

Me.txtCustomerID = ''

Me.txtCompanyName = ''

Me.txtAddress = ''

Me.txtCity = ''

Me.txtRegion = ''

Me.txtPostalCode = ''

Me.txtCountry = ''

' Hide the command buttons used for viewing

' existing data.

Me.Next.Visible = False

Me.Previous.Visible = False

Me.First.Visible = False

Me.Last.Visible = False

Me.DataEntry.Visible = False

' Show the command buttons used for entering new data.

Me.AddCustomer.Visible = True

Me.ViewData.Visible = True

End Sub

Add Code to Enable Saving the Data You Enter as a New Record

After you've entered record data in a data entry form, you can use ADO to add the record to a recordset. For example, to enable the AddCustomer command button on the customer address form, add the following code to the AddCustomer_Click event procedure:

Private Sub AddCustomer_Click()

' Add the record to the rsCustomers recordset

' in your data-aware class.

With objDataSource.rsCustomers

.AddNew

!CustomerID = Me.txtCustomerID.Text

!CompanyName = Me.txtCompanyName.Text

!Address = Me.txtAddress.Text

!City = Me.txtCity.Text

!Region = Me.txtRegion.Text

!PostalCode = Me.txtPostalCode.Text

!Country = Me.txtCountry.Text

.Update

End With

' Clear the controls for additional data entry,

' if desired.

Me.txtCustomerID = ''

Me.txtCompanyName = ''

Me.txtAddress = ''

Me.txtCity = ''

Me.txtRegion = ''

Me.txtPostalCode = ''

Me.txtCountry = ''

End Sub

Add Code to Enable Returning the Form to Viewing Data

When you've finished using your form as a data entry form, you can return it to its original use for viewing and editing existing records by re-enabling data binding. Any new records you've entered will now be displayed when you move through records on the form. You can also hide command button controls that apply only to adding new records, and show hidden command button controls that apply to viewing existing records.

For example, to enable the ViewData command button on the customer address form, add the following code to the ViewData_Click event procedure:

Private Sub ViewData_Click()

' Bind text box controls to the data source

' of your data-aware class.

Set colBind = New BindingCollection

Set colBind.DataSource = objDataSource

colBind.Add txtCustomerID, 'Text', 'CustomerID'

colBind.Add txtCompanyName, 'Text', 'CompanyName'

colBind.Add txtAddress, 'Text', 'Address'

colBind.Add txtCity, 'Text', 'City'

colBind.Add txtRegion, 'Text', 'Region'

colBind.Add txtPostalCode, 'Text', 'PostalCode'

colBind.Add txtCountry, 'Text', 'Country'

' Show the command buttons used for viewing

' existing data.

Me.Next.Visible = True

Me.Previous.Visible = True

Me.First.Visible = True

Me.Last.Visible = True

Me.DataEntry.Visible = True

' Hide the command buttons used for entering new data.

Me.AddCustomer.Visible = False

Me.ViewData.Visible = False

End Sub

Modifying the Class and Form to Write Records Back to the Delimited Text File

After you've updated records or added new records, you can write the changes back to the delimited text file that serves as the data source for your data-aware class. You can add a public method to the class that writes records to a file, then invoke the method in your applications.

This topic shows how to modify the CustomerDataSource class to provide a public method to write records back to the Customers.txt file, and how to invoke the method on your customer address form.

To modify the class and form to write all records back to the delimited text file

Create a public method in the class that writes records to a file.

Create a command button on your form that writes records to a file.

Note   This topic is part of a series that walks you through creating a simple database application that interacts with data in a tab-delimited text file. It begins with the topic Interacting with Data in an ASCII Text File.

Create a Public Method in the Class that Writes Records to a File

By adding Sub procedures to your class, you can provide public methods to applications that use your class as a data source. For example, you can create a public method in your CustomerDataSource class that writes current records from the rsCustomers recordset to the Customers.txt delimited text file. The text file will then include any changes or additions you've made to the recordset.

To create a public WriteToFile method, add the following code to the CustomerDataSource class:

Public Sub WriteToFile()

Dim fld As ADODB.Field

Dim strRow As String

Dim strField As String

Open 'Customers.txt' For Output As #1

With rsCustomers

.MoveFirst

Do While Not .EOF

For Each fld In .Fields

' If a field has a value, add quotation marks.

If Len(fld.Value) > 0 Then

strField = Chr(34) & fld.Value & Chr(34)

Else

strField = ''

End If

' Add the field value and a tab delimeter

' to the output string.

strRow = strRow & strField & Chr(9)

Next

' Strip off the end tab character.

strRow = Left(strRow, Len(strRow) - 1)

' Print the output string.

Print #1, strRow

strRow = ''

.MoveNext

Loop

End With

Close

End Sub

Create a Command Button on Your Form that Writes Records to a File

Once you've created a public method in your data-aware class, you can use it in any application that requires the same functionality. For example, by creating a public method for writing records to a delimited text file, you can easily create a WriteToFile button on your customer address form. The command button requires a single line of code.

To create a WriteToFile button, add a command button to the form and change its Caption and Name properties to WriteToFile. Then add the following line to the command button's WriteToFile_Click event procedure:

objDataSource.WriteToFile

The code uses the WriteToFile method you created for the CustomerDataSource class.

You may want to hide the WriteToFile button while users enter data on the form. To hide the command button during data entry, add the following code to the DataEntry_Click event procedure:

Me.WriteToFile.Visible = False

And if you hide the WriteToFile button while users enter data, make it visible again while users view data. To do so, add the following code to the ViewData_Click event procedure:

Me.WriteToFile.Visible = True


Nu se poate descarca referatul
Acest document nu se poate descarca

E posibil sa te intereseze alte documente despre:


Copyright © 2024 - Toate drepturile rezervate QReferat.com Folositi documentele afisate ca sursa de inspiratie. Va recomandam sa nu copiati textul, ci sa compuneti propriul document pe baza informatiilor de pe site.
{ Home } { Contact } { Termeni si conditii }