http://www.developer.com/

Back to article

Visual Basic Tutorial - Part 5


November 5, 2002

Welcome to another edition of my amazingly simple Visual Basic tutorial. And if you don't think it's simple - that's fine. Just don't tell the Editor.

If this is the first time you've discovered us, you're late! We already have four editions available on the Net. Surf down to the previous tutorials with these links -

In this tutorial, we'll be revisiting those halcyon days of early tutorials with another look at the mysterious world of objects and their related properties, methods and events.

Then we'll be moving on to "functions". Trust me, these things are SOOO useful!

So without further ado, let's code - geek to geek!

In this section, we're going to run over some old turf. I'll be skimming over a few key topics we covered during the past few tutorials to ensure you're all keyed up for the "function" leap.

Confused by methods, events and properties?

If you get bored, that's fine. Just take a quick walk. Or go swimming. Or try hitting a fellow programmer. Or throw your computer out of the window. Or try asking a foreigner for technical support (ps. undertaking any of these actions may result in a serious health decrease).

I've blabbled on about objects and their properties and events before - and have lightly touched on "methods" - but we've never really explained them in great depth. In this section we'll be running these real-life programming scenarios alongside an interesting (and rather tasty) analogy that will have you crying "eureka!" within the hour.

You can liken programming objects to real-life things. I know you like pretending, so let's imagine an orange in a nerd's world. Each orange would have properties, methods and events.

One such property of the orange could be its colour. The default would probably be orange, but in the wonderful Windows world, you'd be able to change that with a small piece of code like:

Orange.Colour = Green

Wow! Imagine the dollars you could earn selling novelty green oranges!

You can read and write most properties in code - in other words, you can set their properties using code similar to the above - or read them in code like:

MsgBox "The colour of your orange is " & Orange.Colour

Other properties of the orange may include Size (measured on a scale of 1 to 10) or Poisonous (True of False). We've dealt with properties before. Remember when we set the Caption, Font and Name properties of our command buttons?

The orange also has "methods". A method is just something that happens. Remember we talked about subs in the last tutorial? A method is just a sub that refers to this particular object. So, your juicy orange may have a "Slice" method or an "Eat" method. To run such a method, you simply use the code:

Orange.Eat

or

Orange.Slice

Make sense? Hope so. We've not encountered many object methods to date - but let's take a few examples. You may be creating a spreadsheet like program and use the method:

Spreadsheet.AlignAllColumns

Or perhaps:

Game.EnterCheatMode

In brief, a method is just a piece of code you fire off that often affects the object you're working with.

And last, but certainly not least are events. Events are little triggers that tell your program when something has happened. So you might put the orange into your Visual Basic program - and you need to know when the user takes a bite, so you can add it onto their current bill.

How do you do it? You simply respond to an event. We've used events before - remember we put code under the Click event of our command button to display a message box? That's all an event is. When something happens in the object, it tells Visual Basic - and you can throw a bit of code together to respond to that particular event if you wish.

Your code usually looks something like this:

Private Sub Command1_Click()

  MsgBox "You clicked me! Don't do that again, sonny!"

End Sub

The first "Private Sub" line and closing "End Sub" are automatically added by Visual Basic when you select the event from the code window. They simply define the code boundaries.

The code for our orange probably looks something like this:

Private Sub Orange_TookABite()

MsgBox "I know you've just taken a bite!"
Msgbox "This code runs whenever the TookABite event of the Orange objects fires up!"

End Sub

Likewise we could add code to respond when a user clicks on a command button or changes the value of a text box - just by entering code under the appropriate event.

I hear you crying "Eureka!" at this point. You've finally figured out what I've been boring you with over the past few weeks. Why, I hear you cry, have I saved this simplified analogy from you for so long? Two reasons -

  • (a) Because the comparison is too simple for you to grasp during those early days - without a proper hands-on look at what's happening behind the scenes
  • (b) Because I enjoyed watching you sweat the past four tutorials
  • (c) Because I'm a small, evil man with a horrid cackle and an in-built urge to rule the world. Hahaha! Hahahahahaha! HAHAHAHAHAHAHAHA!!! Ohh. Sorry. Errm, yes. Sorry about that. Must learn to control myself in public

[Ed: That's three reasons, Karl!]

Anyway, enough of that. Lets move onto "functions" - a really, really cool thingy in Visual Basic.

Functions are probably the most important thing you'll learn in this entire course. They're useful, they're efficient, they're clever - but they take a fair while to get your head around.

What is a function and how is it different from the standard "sub"?

A function is really just an over-rated Sub. Remember that a Sub is just a piece of code that runs. It can also accept "arguments", such as a number or string of words that it processes in its code.

A function is just the same - except it returns a value.

For instance, I may have an application that takes two numbers from two different text boxes, adds them together and then displays the result in a message box. No problem there.

My form looks something like this -

The code behind my first command button might look something like this -

MsgBox Text1.Text & " plus " & _
Text2.Text & " equals " & Text1.Text + Text2.Text

That's great. Now my code behind the second command button would look something like this -

MsgBox Text3.Text & " plus " & _
Text4.Text & " equals " & Text3.Text + Text4.Text

Now on a form with four different command buttons, a line of code similar to the above would have to be added behind each command button.

What if my boss approached me and requested the two numbers be multiplied by each other, as opposed to simple addition? I would have to change the code behind every single command button.

That's pretty simple when you're only adding a couple of numbers together. But when you've got a complicated piece of code that changes values in databases, performs complex calculations and calls Windows API functions - you really don't want to have to change all that code behind every single command button.

Wouldn't it be great if you could create one generic piece of code that handled the core processing - plus took into account any individual needs? That's where functions come into play.

Before we look at a sample snippet, bear this in mind - a function always returns a value. All will become clear -

Public Function AddThemUp(NumberOne as Integer, NumberTwo as Integer)

  AddThemUp = NumberOne + NumberTwo

End Function

I'll explain this example function step-by-step. The first line is pretty similar to the first line of a Sub. It simply states this is a function called AddThemUp which accepts two arguments, NumberOne and NumberTwo - both of which are integers, aka numbers.

The second line does the actual work. It says that the "result" of this function is equal to NumberOne plus NumberTwo.

The last line merely defines the end of the function.

Let's say we added this function to the code underneath our form, then added a command button with the code:

MsgBox AddThemUp(1, 2)

Upon clicking the button, we would get a message box displaying the number three.

Let's run over how this is happening. In our MsgBox code, we're telling VB to run the AddThemUp code, supplying it with the required arguments - NumberOne and NumberTwo - which are the numbers 1 and 2 respectively.

When the code finishes running, it sets the value of the function to our calculation's result. Remember I said a function returns a value? Our code simply sets that function value with the code "AddThemUp = Whatever".

Then whenever the function is referenced with a piece of code like "MsgBox AddThemUp(1, 2)" - the AddThemUp bit runs the function and returns the value.

Try building an application that uses the function we created to solve our initial problem with the numerous text boxes and four command boxes.

In the code behind the command button you can put something like -

MsgBox Text1.Text & " plus " & _
Text2.Text & " equals " & AddThemUp(Text1.Text, Text2.Text)

So if my boss now requests the two numbers be multiplied by each other - I only need to change the code behind one function as opposed to four command buttons.

Functions needn't be simple. Karl explains some practical uses for functions...

Don't forget that a function doesn't have to be as simple as ours. It could contain dozens of lines - perhaps looking in a database of logged-on users and returning a True/False value depending on whether the user is in the table. The function code would go something like this

  • Log onto database
  • Open logon table
  • Check if user is in list
  • If user is in table, set the function value to True - otherwise set it to False

Of course, that's all pseudo-code. Real life coding ain't that simple. Hey, comon - ce la vie!

Then you could use the function like this -

If UserLoggedOn("Jane")=True then
  MsgBox "Jane is logged on!"
Else
  MsgBox "Jane isn't logged on. Sorry!"
End If

Whew! That's a lot to take in. But when you figure out the absolute simplicity of the entire function concept - you'll have sussed Visual Basic. Well done!

Karl concludes this week's epic article.

This week, we've taken another peek at properties, methods and events. We then took a worthwhile look at functions. You see - as I stated in the last tutorial - they're just Subs with frills!

Next week, I'll be finishing the tutorial. Uhuh, hold back the tears, but it must be done.

I'll be answering all the common questions you've sent my way, plus recommending where you should go from here.

Until then, this is Karl Moore speaking live from VB-World.net. Are you receiving me, Roger? Over and out, and goodnight for now. Goodnight!

Karl's Visual Basic Tutorial Index

Visual Basic Tutorial
Visual Basic can be confusing, especially for newbie programmers. But don't worry - here to help is technology journalist and head geek Karl Moore, with the first installation of his up-and-coming Visual Basic tutorial!

Visual Basic Tutorial - Part 2
Karl Moore returns with the third instalment of our exclusive no-geek-speak Visual Basic tutorial. This week, Karl gets his hands dirty with variables and conditional logic, so get out your nerds dictionary!

Visual Basic Tutorial - Part 3
Karl Moore returns with the third instalment of our exclusive no-geek-speak Visual Basic tutorial. This week, Karl gets his hands dirty with variables and conditional logic, so get out your nerds dictionary!

Visual Basic Tutorial - Part 4
Karl Moore gives you the buzz about looping, grabbing information from users and subs, as always without geek-speak!

Visual Basic Tutorial - Part 5
Karl Moore returns with another geek-speak free guide to Visual Basic coding. This week, Karl explains what methods, events and properties actually are, as well as delving into the enigmas that are functions. Lets code geek-to-geek baby!

Visual Basic Tutorial - Part 6
Head geek Karl Moore returns with the final instalment of his popular jargon-free VB tutorial!

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date