18. Mixing types

So you should now have finished the first two items on our Flow of Logic from back here which leaves us with the variables to reset, the labels to update and the button to disable. Let’s start with resetting our “xWins” variable back to zero:

xWins = 0

Pretty simple huh? The only thing to note here is that because “xWins” is of the data type “Integer“, we don’t need double quotes around our number. Numbers are always added to variables and manipulated without quotes of any kind!

Now what about updating the label? This is a little trickier because we want the label to contain some text as well as the number that’s in the “xWins” variable. Here is the correct code and then I’ll explain how it works:

lblCrossWins.Text = "Number of X wins: " + Trim(Str(xWins))

While it may look like a simple line there is actually quite a lot to understand about this. Remember that if the computer sees an equal sign it evaluates what is on the right-hand side first, i.e:

"Number of X wins: " + Trim(Str(xWins))

We have a string inside the double quotes and after that we have used the “plus” operator ( + ) to add something onto the end of our string, that “something” is:

Trim(Str(xWins))

The brackets are important in helping us break down what is happening here, start with the inner-most section which says:

Str(xWins)

What we have done is tell the computer to run the “xWins” variable through what’s called a Function. The name of that function is “Str” and you’ve probably already worked out what it does…that’s right, it converts whatever is inside the brackets into the data type “String“.

So now that “xWins” has been transformed into a “String“, it matches the type of information that can be put into the “Text” property of the “lblCrossWins” object. The only element not explained is why we have used the “Trim” function:

Trim( ... )

This simply takes any extra space off the string inside the brackets. During the conversion from “Integer” to “String” VB often adds spaces so this “Trim” function just removes them.

Okay! We’ve turned what seemed like a simple line into what now appears to be a complex one, but it’s important to understand everything we encounter thoroughly so explaining things thoroughly now will only help us later.

3 thoughts on “18. Mixing types

    • Think of a “string” as a series of characters all “strung” together. The word “Hello” for instance is just “H” + “e” + “l” + “l” + “o” all pushed together to make one word. If you wanted to add a space onto the end of that you could do so by saying “Hello” + ” “. A character is basically anything you can type on the keyboard.

Leave a Comment

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>