You are on page 1of 9

Tutorial 3: Accessing databases using the ADO Data Control

Contents:
• • Download and Run Example Program Build Example Program 6 from Scrach o Database Design o Software Design

Download and Run Example Program
Okay, this is the promised ADO example program. It's exactly the same as the example I did for the Data Control and the FlexGrid, but with a few added bells and whistles. Also, it works right away with an Access 97 or 2000 database, which makes things much more convenient. Okay, let's get into this thing:

Okay, the steps to follow: 1. Just save the file to your desktop. 2. Double click the file to open it with winzip. 3. Click "Extract" and extract the file to your desktop (note: you need to extract both files). 4. On your desktop, you should now have a folder called "ADOExample" 5. Go in there and double-click "Projcet1.vbp" (.vbp stands for "Visual Basic Project") 6. Now, you should get VB loaded up with that project, no problem! With that going, you can push the play button (center of the top tool bar) and see what it looks like. There are a couple of things you can do with it: • You can add CDs to the Database by entering some info in the textboxes and pushing the "Add This Info" button o This has changed: now, the "Add Entry" button will not enable until all three textboxes contain text. o The "Track Count" textbox will only accept numeric characters o This program does not check for duplicate entries in the database. If you do that, it'll crash. :) • You can select a row from the grid and hit the "Remove Selected" button to remove it permanently from the database • The form now resizes properly. So, if you resize the form, the grid and frames will resize appropriately (to a certain point)

Build Example Program 6 from Scratch:
Okay, let's get down and dirty. :) This one's quite a bit bigger than the other one (although the bigger is more or less useless stuff that was thrown in for fun, haha!).

The Database Design 1. Open up MS Access (Start - Programs - Microsoft Access) 2. Pick "Start a blank database" from the wizard that pops up 3. Pick a spot to save the mdb file and a name for it (mine was
"CDCollectionA.mdb") in design view:"

4. You'll get to the following window, where you double click on "Create a table

the database design main window

5. When you double click that "create table in design view" thingie, you get to
this window:

The table design view window

6. You want to follow the following steps to get the table I was working with: 1. Make a field called ArtistName whose type is Text 2. Make a field called AlbumTitle whose type is Text 3. Make a field called Tracks whose type is Number (just a long integer is
cool enough)

4. Select the rows in the design view (as pictured above) that have
ArtistName and AlbumTitle 5. Right-click on that selection, and pick Primary Key from the menu you get. This will make both fields into primary keys. The idea is that they can be primary because you'll never have identical artist names and album titles (otherwise what's the point?!). Once you've got your table built, just close that window. You'll be automatically prompted to save changes to the table design and to give the table a name. I picked CDs, how original. :) Once that's all done, you can either add a couple entries to the database by double clicking the CDs table from the database design main window and inputting them manually or just move on to:

7. 8.

Software Design
Okay, as mentioned at the top of this article, we're going to use the ADO (ActiveX Data Objects) data control for getting at data instead of the common data control used in Example 3. I know what you're thinking: who cares. :) In any case, ADO can provide you with a little more customizability and a little bit more speed, but it's also a little more difficult to use. No problem, though, there's a cheap way around everything, so let's dive right in. 1. First thing first, start up VB with a Standard Exe project. 2. Go to the Project menu and select Components (near the bottom). You want to add two new controls to your project: o the Microsoft ADO Data Control (OLEDB) and o the Microsoft Hierarchical FlexGrid Control 6.0 (note this is not the FlexGrid as used in Example 3)

the add components dialog

3. Okay, now do the following stuff to your main form: 1. Change the caption of your main form to something hip and jive ... 2. Add a Heirarchical FlexGrid to your form by picking the
drawing it on your main form. tool and

3. Add an ADO data source control to the form using the 4. Add two frames to the form using the

tool and drawing on the form. Change its visibility property to False. tool and drawing them on the form.  Change for one frame:  its caption to Add Entry  its (name) to fraAddEntry  Change for the other (second) frame:  its caption to Remove Entry  its (name) to fraRemoveEntry Draw the following controls in the Add Entry frame (yes, actually in the frame): A text box with the (name) txtArtistName A label above that text box with the caption Artist Name A text box with the (name) txtAlbumTitle A label above that text box with the caption Album Title A text box with the (name) txtTrackCount A label above that text box with the caption Number of Tracks

5.

A command button with the (name) cmdAddEntry and the caption Add this info 2. Now, to the Remove Entry frame, add the following controls: A command button with the (name) cmdRemoveEntry and the caption Remove Selected A label with the caption Select the entry you want to remove and click the button: 4. Now, the most complicated part is formatting the Heirarchical FlexGrid (which is called MSFHlexGrid1) to do what you want. It's fairly customizable, but here's all I did for this example program: 1. the AllowBigSelection property was set to False 2. the AllowUserResizing property was set to 0 3. the FixedCols property was set to 0 while the FixedRows property was set to 1 (this is recommended for pretty displaying of stuff) 4. the FocusRect property was set to 0 5. the HighLight property was set to 1 6. the ScrollBars property was set to 2 7. the ScrollTrack property was set to True 8. the SelectionMode property was set to 1 (selection by row only) 5. In the form design window, double click the form, which should bring up the code window with a blank Form_Load() subroutine. o You'll notice this time that we do the data and database hookup in code instead of in the property sheet. For the ConnectionString property of the ADO Data Control, you can build it in the property sheet. There's a wizard in there that will do it from scratch for you, but it's pretty annoying to surf through. That's why I just included this string instead (it was built in the wizard though) You need two global variables, and they appear right above the Form_Load() method. For the FlexGrid DataSource, note that the Set command/directive/whatever is used!! Here's the code: Option Explicit ' couple'o global vars to track the form minimum size Dim MinHeight As Long Dim MinWidth As Long Private Sub Form_Load() ' set up the database connectivity for the ADO data control With Adodc1 ' the connection string just defines an interface to connect ' to the Access database. We use the MS Jet SQL drivers for ' simplicity's sake. Side-note: you can build your own connection string ' from the property sheet for the ado data control, but I would advise ' against it, this is easier. :) .ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _

App.Path & "\CDCollection.mdb;Persist Security Info=False" ' the record source just tells the data control what and how ' to pull out of the database. Just raw SQL here. .RecordSource = "select * from CDs order by ArtistName" End With ' set the Flex Grid data source to be the ADO data control. Set MSHFlexGrid1.DataSource = Adodc1 ' set up the format string for the flex grid. MSHFlexGrid1.FormatString = "Artist Name | Album Title | Track Count" ' position all the controls happily and store the form minimum size MinHeight = Form1.Height MinWidth = Form1.Width Call Form_Resize End Sub 6. Okay, that's done. From the event ComboBox at the top of the code window, pick the Resize event. You should then get a shell for the Form_Resize() method. This gets called whenever you resize the form, and we'll just use it to make a resized form look pretty. Here's what to fill in: Private Sub Form_Resize() ' check to see if the form is getting too small (Note: this is just to avoid ' the math necessary to shrink all the textboxes, hahahaha!!) If MinHeight > Form1.Height Then Form1.Height = MinHeight Exit Sub ElseIf MinWidth > Form1.Width Then Form1.Width = MinWidth Exit Sub End If ' resize the flexgrid to fit nicely on the screen MSHFlexGrid1.Width = Form1.ScaleWidth MSHFlexGrid1.Height = Form1.ScaleHeight / 2 ' resize the happy columns column, 20% for Track) MSHFlexGrid1.ColWidth(0) = MSHFlexGrid1.ColWidth(1) = MSHFlexGrid1.ColWidth(2) = (MSHFlexGrid1.ColWidth(0) * 2) to look pretty (40% for each text 0.4 * MSHFlexGrid1.Width MSHFlexGrid1.ColWidth(0) MSHFlexGrid1.Width - 60

' reposition and resize the frames on the screen to fit nicely (there was no ' science here, just did it by trial and error) fraAddEntry.Top = (Form1.ScaleHeight / 2) + 100 fraAddEntry.Height = (Form1.ScaleHeight / 2) - 150 fraAddEntry.Width = (Form1.ScaleWidth * 0.64) fraRemoveEntry.Height = (Form1.ScaleHeight / 2) - 150 fraRemoveEntry.Top = (Form1.ScaleHeight / 2) + 100 fraRemoveEntry.Width = (Form1.ScaleWidth * 0.36) - 100 fraRemoveEntry.Left = fraAddEntry.Width + 100

End Sub 7. Now, go back to the form design window and double click the Add this info button. You should now have a blank cmdAddEntry_Click() subroutine. The code is pretty much identical to the old database example, but here's what to fill in, anyways: Private Sub cmdAddEntry_Click() ' add a new entry to our table. With Adodc1.Recordset .AddNew !ArtistName = txtArtistName !AlbumTitle = txtAlbumTitle !Tracks = txtTrackCount .Update .Requery End With ' refresh the data source and rebind it to the flexgrid (annoying!!) Adodc1.Refresh Set MSHFlexGrid1.DataSource = Adodc1 MSHFlexGrid1.FormatString = "Artist Name | Album Title | Track Count" Call Form_Resize ' clear the text fields once the new record is added txtArtistName = "" txtAlbumTitle = "" txtTrackCount = "" ' set the focus back to the artist name textbox txtArtistName.SetFocus End Sub 8. Now you need the remove code. In the form design window, double-click the Remove Selected button. You should get a shell for the cmdRemoveEntry_Click() subroutine. This is the code: Private Sub cmdRemoveEntry_Click() ' delete an entry from the database With Adodc1.Recordset .Move (MSHFlexGrid1.Row - 1) ' we minus one because row zero is the header row .Delete .Requery End With ' refresh the data source and rebind it to the flexgrid (annoying!!) Adodc1.Refresh Set MSHFlexGrid1.DataSource = Adodc1 MSHFlexGrid1.FormatString = "Artist Name | Album Title | Track Count" Call Form_Resize ' set the focus back to the first add field txtArtistName.SetFocus End Sub 9. Okay, if you go to the form design window, you have three textboxes: txtArtistName, txtAlbumTitle, and txtTrackCount. Double click on each of

them in turn to get their associated Change methods and fill in the following code: Private Sub txtArtistName_Change() ' here, just check to see if each text field has contents. If they all have ' contents (ie, they're not empty) enable the "Add Entry" button. If txtArtistName.Text <> "" And txtAlbumTitle.Text <> "" And txtTrackCount.Text <> "" Then cmdAddEntry.Enabled = True Else cmdAddEntry.Enabled = False End If End Sub Private Sub txtAlbumTitle_Change() ' just call the artist name change method because the code here would be ' exactly the same. Call txtArtistName_Change End Sub Private Sub txtTrackCount_Change() ' just call the artist name change method because the code here would be ' exactly the same. Call txtArtistName_Change End Sub 10. While you're still in the txtTrackCount_Change() method, go to the event ComboBox at the top of the code window and select the KeyPress event. You should get a shell for the txtTrackCount_KeyPress(KeyAscii as Integer) method. Here's the rest of the code for that, it just filters out alphabetic and punctuation characters: Private Sub txtTrackCount_KeyPress(KeyAscii As Integer) ' TrackKey will store which key was pressed in an _ascii_ value. Dim TrackKey As String TrackKey = Chr(KeyAscii) key, ' if the key pressed was a)not a number and b) not the backspace

' just erase the keystroke (it won't get processed or sent) If (Not IsNumeric(TrackKey) And Not (KeyAscii = vbKeyBack)) Then KeyAscii = 0 End If End Sub