Download as pdf
Download as pdf
You are on page 1of 9
12 _ Working with the Data Control Inthis chapter we will cover 2 Manipulating the database with the Data Control In the last chapter we created tables using the Visual Data manager. We saw how we could modify the tables, add or delete or rename fields, All this may give you the idea that changes can be accommodated at any point in the software development process. However, this is not trie, One has to take great pains in terms of designing the database. A good design can make software development and maintenance easy. A poor design and an ad hoe approach will get you into trouble, Since designing the database is of great importance, let us take some time to look atthe issues involved in designing a database: The Data Control (database can be created easily with the help of the Visual ata Man: Bar ‘The tables can be bopulated by simply entering the data in the respective fields Next Watiocd to create an appli- ‘ation to display the data from the database, and allow the users to add new records or modify existing data, ae we bos create such an application wehave to Establish a connection with the database. Extract the fields from the relevant tables. Display them on the form. Accept changes made to the data on the form and update the database.) TR Viswal Basie 6.0 asic is meant to reduce the am dows environment. Develop," | Basic. In order to meee 4° e the above job very simple, This sounds like a lot of work indeed, However, V ane of coding and speed up application development for th . a database application is considered to be very easy Wit an objectives, Visual Basic provides the Data control that wl & e ) tor ths (The Datacontrol ip YR wo vse? 1. Establishes a connection to a database. 2. Returns a set of records from the datab: 8. Enables you to move from record to record. in bound controls. 4. Enables you to display and manipulate data from the records done without writing any code. The data from the database vate the currey played in ‘Data-aware’ controls. Any changes made to the data in the ‘Data-away controls are conveyed to the Data control. The database isupdated to reflect these chang. automatically once the Data control moves to the next, record The next record now becomes current record, and the data is displayed in the Data-aware controls. is How does the Data control Work? In order for the Data control to deliver the goods, two properties need to be set, These proper ties can be set at runtime or design time. The properties are DatabaseName ‘This specifies the name of the database that must be opened. RecordSource ‘This specifies the name of the table(s) of the database from whicht# data has to be extracted. Wy wt When ydu rurthe p rogram after setting these properties, Visual Basic connects to | returns a set of records from the table(s) in the form of a Recordset A Recordset is an object that points to the di returned, based on the RecordSource property of can be the i of a table in the database or an SQL database specified, and “ol. The RecordSource prol statement one more tables. nt that selects fields from Using the Data control Let us take a look at the Data contro The Data control j like this. "ols part of the standard toolbox I Working with the Data Control 183 MovePrevious ws MoveFirst ¢——H4] 4 [Datat MoveLast Movenext {thas buttons for moving from record to record, You have buttons to move to the next or last ord and to move to the previous and first record JYou can also set the caption property for the jatacontrol- ° setting the Properties for the Data Control \ewill take a look at/the important properties of the Data controla.2 j0FAction: Action to be taken when the user reaches the beginning of File. 10FAction: Here we tell the Data control what to do when we reach the end of File. (Caption: The text to be displayed on the Data control's title bar. (Connect: This tells the Data control the type of database that will be accessed. It could be TuPro, dBase, Paradox, Access, etc. The default is Access. DitabaseName: Specifies the name of the database that the Data control will access. Give the ume of the file that contains the database. Hard coding the name here is not a wise thing to do. ‘ean be set at runtime. 'ecordset Type: This property specifies the type of Recordset object the control will use to ‘sess the database, There are three options: 1. Table. 2. Dynaset. 3.Snapshot, %cordSource: The RecordSource property specifies the source of the records accessible through 7 \dcontrols on your form,) If you set the RecordSource property to the name of an existing 7 lein the database, all of the fields in that table are visible to the bound controls attached to Data control. Sample “tscreatea program that will display the records in a database, We will use the Invoice.mdb Creating the Form Start a new project, om the Data control to the Form. 8? TextBox controls Ad one CommandButton two LabelBox controls. 84. Visual Basic 6.0 Your Form will look like th Setting the Properties Click on the Data control and bring up the Propertie: 1 .s window. Click on Name: Let us call it Customerdata. We will be referring to the Data control with this name. Click on BOFAction. Set it to MoveFirst. e is reached, the Data control must be told to poin When the Beginning of Fil t to the first record. Click on Caption. Set it to Customers. This will be # default is Datal. Click on the Connect Property. Select Access. Access is the default. .e of database that will be used. Visual Basic can W' he title of the Data control. The ‘This tells Visual Basic the typ ork with a number of other databases. Click on DatabaseName Property. We have to mention the name of the MDB file that must be opened by the Data Cont For this example select C:\azam\vb-exersices\Invoice.mdb. This pathname will & pend on where you ereated the mdb file. Check your file system before you assign veime, Later we will see how not to hard code the full pathname of the file. Click on EOF Action. Set it to MoveLast. ‘This tells the Data control to point to the last record when the user reaches the End® File. ill cyek on Recordeet Type Property, so ‘Type property de Ree y determin pala control, The options are 1 Working with the Data Control 185 leet O-Tabs type nes the type of object that will he created by the ‘Type where an editable Recordset is created pased on data from a single table, 2 Dynaset where an editable Recordset is created pased on data from one or more tables. 3. Snapshot, where a non-editat Heated based on data from one > Recordeet ie or more table. lick on RecordSource Property. Set it to Customer. Data in this property we tell the Data control the table or query that must be used while seating the Recordset, ‘okay go you have now specified the settings, so to say, However, running your program at age will not display any of the records, That is because the other controls on the form »** tbeen ‘bound’ to the Data control. wt The Bound Controls Sineofthe controls can be ‘bound’ to the Data control, Each bound control is bound to one field lhe Recordset. They display the fields from the current record of the Recordset. Depending 7 tei properties, they may also allow the user to edit the data displayed and pass the edite “aback to the Data control. The following controls are all data-aware and can be bound to a single field of a Recordset “auged by the Data control. label TextBox CheckBox Image OLE ListBox 186 Viswal Basic 6.0 Picture CombeBo: x g sets of records when bound to 4 ayed or manipulated at ong, The following controls are all capable of managin’ control. All of these controls permit several records to De DBList DBCombo DBGrid ) Binding the Bound Controls i r to make the a eee Gaede a TextBo, Data aware, we need to bind it to the Data control. This is how we 6 Select Text]. Bring up the Properties window. 1. Click on DataSource Property. Set it to Customerdata, This is the a of the Dat, control. From now on this text box will display a field from the Recordset returned py the Data Control. 2. Click on DataField. A list of fields available will drop down. Select Customer_Name, ‘This TextBox is now bound to the column Customer_Name. It will display the current recor} of the Recordset, When the user moves from record to record using the navigation buttons the Data control, it will display the Customer_Name column of the current record. Next select Text2. Set the following properties DataSource: Customerdata DataField: Amount_Due. For the CommandButton click event, add the statement End in order to terminate this program. Set the appropriate captions for the LabelBox controls. Now run the program, Click on the buttons on the Data Control and watch as record aft record is displayed in the textboxes, without writin, i | i g any code, Mak inthe textbox and check ifthe changes aro updated in the database, a. a cave We saw how easy it is to create a simple application. The the mumbo-jumbo that programmers like to talk about| record navigation; it can accept changes and also re was no coding or looping oF #” i \he Data control automatically ha” update the changes made to the 188 Visual Basic 6.0 Your form will look like this Customer Name | scgoset Find What? [ Adding a New Record add the necessary data) In thiscas To add a new record, you need a blank record id the data, the new record must}; sou have to add the Customer Code, Name, e , “addNew’ meth ‘added to the table{In order to add a new record we must invoke the ‘AddNew method, which will create a blank record in the memory. ‘This blank record becomes the current record. After by either of the following method: vin enter the data, you can add thenew record to the database 1. Moving to another record. 2. Invoking the ‘Update’ method. 2 (aaa the following code to the Add button. ) ( ( ‘The AddNew method adds a new record at the end of the file, and clears the contents ofthe In order to set the focus on the TextBox where you will enter the Customer Code, at! Sub CmdAdd_Click) ata eecsrdset -addniew.) stomerd: textboxes, the next‘ine. ccode. SetFocus End Sub Deleting a Record Tn order to delete a record, we have to invoke the ‘delete 1 i displayed will get deleted. Once this record is deleted, wo a ‘h od. The current record a " ist move the record pointer Working with the Data Control 189 record, This is because the record pointer will continue pointing to non-existing record sat fpe current record has been deleted. Although the record ia deleted in the database, the io ill be still visible to the user. When the user clicks on the delete button (with more force) a and time, an error will occur. To avoid this situation we need to add some code, Your code ike this, i eee 1 e Sub CmdDelete Clicky rivat ~,stonerdata Recordset .Delete \ “the delete method deletes the current record. In order to move to the next record,add the atline customerdata Recordset .MoveNext, end Sub However, there is another problem here, Let us say that you are deleting the last record. If guinvoke the ‘MoveNext’ method after deleting the last record, you will get a message saying ‘ocurrent record’. In order to avoid this, your code needs to be modified. The modified code sillook like this. customerdata.Recordset .Delete If Not Customerdata.Recordset .EOF Then Customerdata.Recordset .MoveNext. Else Customerdata. Recordset .MoveLast End If ‘\pdating the Database TeeData control itself handles the task of updating the database with the changes made to the ‘rent record, when you move the record pointer to another record. Jf you want to explicitly ‘lthe update routine, you can do so with the following code. y (trate Sub CmdUpdate_Click) \ “ustomerdata.UpdateRecord the record entered after clicking on the Add Button will now get added to the database. q ‘Wtomerdata. Recordset .Bookmark = Customerdata. Recordset . LastModified This line is added so that the control returns to the record that has just been updated. ‘Otherwise the control returns to the first tecord, Xd sub 190 Visual Basic 6.0 — Exercise —— 1 Add the necessary code to edit/modify a record. Write the code for moving to next, last, pre, 2 Add buttons for navigating the database ous and the first record. UpdateRecord and UpdateControls Method Data control. The UpdateRecord method allows the users These methods are special to the h ‘e editing, This will be of great use when ¢ save the changes to the current record and continu! number of fields to be edited on the form is large. of the above. This method will be of use whe The UpdateControls method does the reverse ade to the current record before updating. the user wants to roll back the editing changes m: Finding a Record Users of our program will find it very tedious to.glickyaway and till they reach the record they want to view. We need td provide‘a shortcut to enable thenrto view a particular record. us use the Find method. r (The Find method works only when the Recordset type is a Dynaset.or snapshot. If th Recordset type is set to Table type, then you have to use the Seek method. Private Sub CmdFind_Click) . ‘Customerdata.Recordset. FindFirst “Customer_Name =“ & Trim(Text3.Text) & “* ) ind Sub 7 The FindFirst method looks for the first record where the Name Column matches the te entered in the FindTxt textbox. The record that contains the matching text will become the current record. If no matching Name is found, the data control will remain silent. Run the application. Try out the Find facility,

You might also like