People with no previous programming experience will find that Visual Basic is the best place to start. Progressively harder languages such as C, C++ and Assembler will fill the other rungs of the ladder but for now you must not set your targets to high. By all means set yourself a goal or "carrot" - that always helps when learning a language, you may never accomplish that goal but the experience gathered by trying to reach it is invaluable.

This section is aimed at complete novices, people with previous programming experience are welcome to follow this tutorial but I doubt it will teach them anything they don't already know. In my opinion, the hardest part of learning a programming language is getting your head round the structure of it. I'm afraid that no book or tutorial can teach you this - as you program more and more you will develop your own programming style and soon the structure of the language will become second nature to you.

The VB4 Tutorial assumes you've read and understood the Visual Basic 3.0 Tutorial. Ok, we need a program to work towards. hmmm, any ideas? Good idea! We'll write a database application that encompasses many sides of Visual Basic and also demonstrates good programming by not using the VB data control!


Part One - Designing the application...

First things first, load Visual Basic 4.0 32-Bit. Start with a blank form. For this example we'll need:

  • 2 Text Box's on the form.
  • 1 List Box.
  • 5 Command Buttons.
  • 1 Frame
  • 5 labels
  • Ok, now we have the ingredients it's time to mix them all up on the form until we have a nice looking front end as shown below. Note: You don't have to design the screen this way, you are free to design it the way you want but for the benefit of the tutorial, we advise you to copy ours :)

    VB4 Tutorial Screen 1

    Does your's look like this? Goodoh, lets procede then. Make sure you do overlap the two buttons shown above, this is cheating we know, but it's just an example of how you can get away with easier programming in VB :) Time to set the properties of each control.
  • 2 Text Box's: Set the Name property on both to "db_show" and change the index of the first to "0" and the second to "1". This creates a control array - much easier to work with in the long run as you will see later on.
  • 5 Command Buttons: Change 3 of your command buttons' captions to "Add New", "Update" and "Remove" respectively. Give "Add New" an index of 0, "Update" and index of 1 and "Remove" an index of 2. On your fourth button, change its caption to "Save New", set it's Visible property to FALSE and position it over the "Add New" button on the form. With your fifth button, change its caption to "Quit" and position it in the top right hand corner of the form.
  • 5 labels: Place 4 labels and their captions as shown in the picture above. With your final label, place it next to your "Number of records:" label, set its BorderStyle property to Fixed Single, BackColor to &H00FFFFFF (Hex code for White) and change it's Name property to record_count.
  • Excellent! On to the application innards. This is where everyone will probably gasp and decide it's too hard for them to do. PLEASE DON'T think that, I admit it looks difficult, but it really isn't as hard as it looks. Tell yourself to finish the tutorial before deciding!
    Part Two - The actual VB Code...

    Congratulations, the first part is over ;) Now for the code. For this application to work correctly, you will need the VB4TUT.MDB file. This is a Microsoft Access compatible database. You could create your own, but I'm not going to confuse you further by describing how to do it. For the sake of this tutorial, I've done one for you - aren't I kind?!

    DOWNLOAD VB4TUT.MDB BEFORE PROCEDING !!

    Right then, create a directory on your hard drive (e.g. c:\vb4tut\) and place the database file in there.
  • Return to Visual Basic 4.0, design mode.
  • Double click on the Form to bring up the Form_Load event. You will need to type or Cut&Paste the following lines of text into the Form_Load event window (don't forget to cut the HTML comments out!!):
    
    Private Sub Form_Load()
    ' This sets the path of the filename.
    ' The app.path statement is VERY useful as it
    ' returns the directory where the program is installed
    ' wherever it is on your PC.
    dbname = App.Path & "\vb4tut.mdb"
    
    The only failing here, is if you run the program from the root directory of your hard drive. For the moment, App.Path is good enough to determine where the application is installed. The & operator APPENDS "\vb4tut.mdb" onto the directory contained in App.Path - get me? So for example, if you picked up half of a "Merry Christmas" banner, you had the "Merry" (App.Path) side and I had the "Christmas" (\vb4tut.mdb) side, and we'll call your half App.Path. On its own it's pretty useless isn't it? Well I wouldn't hang one up. I have the other half, which again is useless on its own. If I add my half to your half, then we get a full "Merry Christmas" banner that we can hang up without embarrassment (dbname).
    
    ' Set the Database to point to runners.mdb.
    Set Vb4tutDB = DBEngine.Workspaces(0).OpenDatabase(dbname)
    ' Open the table I created called Runners.
    Set tutRS = VB4tutDB.OpenRecordset("Runners", dbOpenDynaset)
    
    The Set command is putting the value of the expression to the right of the equals (=) sign into TutRS - our RecordSet. A record set allows us to perfom functions within the database, such as search, find, move, edit, add, delete etc. It is finding the table I created in the MDB file which I called "Runners" - for no reason at all ;). This table contains 3 columns, "ID", "NAME", "ADDRESS". We will be able to control the table from now on through "tutRS".
    
    ' For some strange reason, VB4 won't return
    ' an accurate record count unless you first move
    ' the database pointer to the last record in the db.
    On Error GoTo process_err
    tutRS.MoveLast
    X = tutRS.RecordCount
    Form1.record_count.Caption = X
    ' Now lets put the names into the Listbox.
    tutRS.MoveLast
    X = tutRS.RecordCount
    tutRS.MoveFirst
    Do
        List1.AddItem tutRS!Name
        Y = Y + 1: tutRS.MoveNext
    Loop Until Y = X ' X = last record remember.
    

    Ok, for those of you familiar with VB3, the Do..Loop won't seem too complicated. All we're doing here is counting through the items in the database filed "Name" and adding each one to the Listbox until we get to the end. I have used the value previously stored in X by the line "X = tutRS.RecordCount" and using it as the stopping point for the loop. The Y variable is simply a counter, starting from 0 and incrementing as the Loop continues. The line "List1.AddItem tutRS!Name" is telling VB to add the value's retrieved from tutRS!Name - our recordset pointing at the "NAME" column in the table. If you can imagine a list of names infront of you on a piece of paper, and you look at each name and type them into a list on your computer then you'll understand what the latter line of code is doing better.
    
    process_err:
    Select Case (Err)
    Case 3021 ' No current record
        record_count = 0
        Exit Sub
    End Select
    End Sub
    
    
    
    Ok, Error 3021 (See VB4Help: Trappable Erorrs) is the code for VB returning the "No current Record" error i.e. the database is empty. If we didn't include error checking routines then our application would crash out each time you deleted all the records in the database. This is of course, unacceptable. The On Error goto process_err is sending the value of the Err object (Contains info regarding Run-Time errors) and then we use the Select Case function to pick out the error we want to trap. In this case error 3021. If it is error 3021 then the code contained after the "Case 3021" statement will be executed - Exit Sub exits the procedure, ignores the error and puts the user back on the main form without crashing the computer. "record_count = 0" simply sets the Record Count label to 0.

    We're doin great so far folks. While you still have the event window open, switch to the Form_Paint even and paste in the following code:

    Private Sub Form_Paint() ' Set the first item to be selected in the listbox. ' Note, count starts at 0 rather than 1. If List1.ListCount = 0 Then GoTo db_empty List1.Selected(0) = True db_empty: Command1(0).Enabled = True Command1(2).Caption = "&Remove" End Sub
    When VB draws the screen layout, it checks to see if the Listbox is empty. It WILL be empty if the code in the Form_Load event was not processed i.e. Error 3021 occured and VB skipped the code so telling us that the database must be empty. At this point the buttons are adjusted apropriately and the Listbox selection set to 0 - nothing.

    Now lets make the Text boxes work. Double click on one of the Text boxes. It doesn't matter which as they are in a control array. They share the same code window. To separate the code for each button we use another Select Case statement with the values of the index of the controls, in this case 0, 1 and 2. However, in this example we don't need to go that far with the text boxes. Cut&Paste the following into the GetFocus event:

    ' This highlights the contents of the text box. db_show(Index).SelStart = 0 db_show(Index).SelLength = Len(db_show(Index))
    The above code highlights the text when either text box becomes focused. A nice little touch. Next, go to the KeyDown event and Cut&Paste the following:
    Private Sub db_show_KeyDown(Index As Integer, KeyCode As Integer, Shift As Integer) Command1(0).Enabled = False If save_but.Caption = "&Save New" And Command1(0).Visible = False Then Command1(1).Enabled = False End If If Command1(0).Visible = True Then Command1(1).Enabled = True End If Command1(2).Caption = "&Cancel" End Sub
    Slightly more complicated. Two IF Statements to check the status of the Command buttons. This determines which button is clicked and adjusts the properties of the other buttons in turn. There isn't much need to go into this as you will soon see that it is very obvious.

    Well, thats the text boxes sorted out. Time to put in the code for the Command buttons. This should be fun ;). Cut&Paste the following into the Click event of one of the command buttons i.e. "Update" button:

    Select Case (Index) Case 0 ' Add New For i = 0 To 1 db_show(i).Text = "" Next i Command1(1).Enabled = False Command1(2).Caption = "&Cancel" List1.Enabled = False db_show(0).SetFocus save_but.Visible = True Command1(0).Visible = False Command1(1).Enabled = False Exit Sub
    The above code is cheating really. All it does is clear the control array using a For...Next loop - see how its done? By cycling through each text box using the index to "grab hold" of the box and clear it. Then it goes on to set the captions of the buttons and enable the "Save New" button which the user is made to click by disabling all other choices but "Cancel".
    Case 1 ' Update On Error GoTo do_errors TutRS.Edit TutRS!Name = db_show(0).Text TutRS!Address = db_show(1).Text TutRS.Update List1.Clear add_names
    Here's some more interesting code. Our friend tutRS is back. This time because we are updating a record i.e. it already exists we just use the .Edit function. You must remember to end an .Edit or .AddNew statement with a .Update to save changes!. The last line of the code points to a procedure that you will manually create in a minute. This contains the same code for the Form_Load event but allows you to process it at any time during your application. Unlike the Form_Load event which is only initialised when you first run the program.
    Command1(0).Enabled = True Command1(2).Caption = "&Remove" Command1(1).Enabled = False Exit Sub do_errors: Select Case (Err) Case 3021 For i = 0 To 1 db_show(i).Text = "" Next i Command1(2).Caption = "&Remove" Command1(0).Enabled = True Command1(1).Enabled = False If Not List1.ListCount = 0 Then List1.Selected(0) = False List1.Selected(0) = True End If save_but.Visible = False Command1(0).Visible = True Exit Sub End Select Case 2 ' Remove If Command1(2).Caption = "&Cancel" Then X = List1.ListIndex For i = 0 To 1 db_show(i).Text = "" Next i List1.Enabled = True Command1(2).Caption = "&Remove" Command1(0).Enabled = True Command1(1).Enabled = False If Not List1.ListCount = 0 Then List1.Selected(0) = False List1.Selected(0) = True End If save_but.Visible = False Command1(0).Visible = True Exit Sub End If If Command1(2).Caption = "&Remove" Then Dim Criteria As String If List1.ListCount = 0 Then Exit Sub Criteria = "Name = '" & db_show(0).Text & "'" TutRS.MoveFirst TutRS.FindFirst Criteria TutRS.Delete
    A little more interesting again! The .Delete will remove the CURRENT RECORD, so first of all we need to tell the database which record to delete otherwise there's going to be chaos. We do this by using the FindFirst method. You have to previously define the criteria to be searched for in a string. Remember the "Merry Christmas" idea? Same applies here with the Criteria = "Name = '" & db_show(0).test & "'". All this is telling VB to do is look in the "Names" field for the first match of what is contained in the first text box. It then deletes it!
    List1.Clear For i = 0 To 1 db_show(i).Text = "" Next i Command1(1).Enabled = False add_names record_count.Caption = record_count.Caption - 1 Exit Sub End If End Select
    I can hear you screaming :) As I said before, it isn't that hard to work out. Each Case statement represents a button. The code between the Case statements is the code to be processed when that particular button is pressed.

    Remember the add_names procedure I was talking about? Yeah, well its time to add it to the application. Double Click on the Form and choose (General) as the object from the code window. Change the Proc: to (Declarations) and Cut&Paste the following code into the window:

    Private Sub add_names() TutRS.MoveLast X = TutRS.RecordCount If X = 0 Then Exit Sub TutRS.MoveFirst Do List1.AddItem TutRS!Name Y = Y + 1: TutRS.MoveNext Loop Until Y = X ' X = last record remember. End Sub
    If you check back, this is exactly the same code as what was in the Form_Load event. We can now call this procedure from anywhere on the form. Here's some more repetetive code, double click on the "Save New" button that you created earlier and Cut & Paste the following into the code window:
    If db_show(0).Text = "" Then Exit Sub If db_show(1).Text = "" Then Exit Sub TutRS.AddNew TutRS!Name = db_show(0).Text TutRS!Address = db_show(1).Text TutRS.Update List1.Clear List1.Enabled = True Command1(2).Caption = "&Remove" Command1(0).Enabled = True save_but.Visible = False Command1(0).Visible = True TutRS.MoveLast X = TutRS.RecordCount TutRS.MoveFirst Do List1.AddItem TutRS!Name Y = Y + 1: TutRS.MoveNext Loop Until Y = X ' X = last record remember. record_count.Caption = record_count.Caption + 1 End Sub
    As you can see, it's just a copy of the "Add New" button code so I won't bore you to death by going through it all again :). Take a breath now folks, we're ALMOST finished, just the module file to do now. Goto the INSERT menu and click on MODULE. In the empty code window Cut&Paste the following:
    Global dbname As String ' This is for the DB filename. Global TutVB4DB As Database ' Create the database. Global TutRS As Recordset ' Create the recordset (Table called Runners within the MDB) ' Global is used to make the variable available ' anywhere in the program. If we wanted to make ' it only available to a particular form then ' it should be place in the General-Declarations ' section of the form.
    The comments explain the above code. Well gues what folks - THATS IT, WE'RE ALL FINISHED! Yeah, congratulations ;) You made it to the end. Hit F5 to run your finished program - after saving of course.
    Part Three - It's Finished - whahey!!...

    Having problems with the source code? You can download all MY source code and the database by clicking here. If you have any questions regarding this tutorial then please email: rad-admin@areti.com with the Subject: VB4 Tutorial.

    Thanks for reading, Tim.