The Times Table Code

As you can see from our last lesson, we've set up five Integer variables - number1, number2, multiplier, answer and i.

The next thing we did was to pass whatever is in our two Textboxes straight into the two variable, number1 and number2. The start number goes into textbox one, and the end number goes into textbox2.

number1 = Val(TextBox1.Text)
number2 = Val(TextBox2.Text)

In the next line of code, we set a starting value for the multiplier variable:

multiplier = 2

The next thing we had was a For Loop. The For Loop was this:

For i = number1 To number2

answer = i * multiplier
ListBox1.Items.Add(i & " Times " & multiplier & " = " & answer)

Next i

Remember: the number1 and number2 variables hold our numbers from the Textboxes. We set these to 1 and 10. So our first line of the For Loop is really this:

For i = 1 To 10

We're saying, "Start a For Loop". Whatever is in the variable called number1, make that the starting number for the Loop. Put this value into the variable called i. The end of the Loop will come when the variable called i has the value 10. Stop looping when you reach this value.

The next part of the code reads this:

answer = i * multiplier

This means, Put into the variable called answer the following sum: whatever is in the variable called i multiplied by whatever is in the variable called multiplier.


Finally, a word about the line that displays your text in the list box. It was this:

ListBox1.Items.Add(i & " Times " & multiplier & " = " & answer)

To add items to a list box with code, first you type the name of your list box:


Type a full stop and a drop down list will appear. Select Items from the list.


Type another full stop and again a drop down list will appear. Select the Add Method


This method, not surprisingly, lets you add items to your list box. Whatever you want to add goes between a pair of round brackets:

ListBox1.Items.Add( )

In between the round brackets, we have this for our code:

i & " Times " & multiplier & " = " & answer

It might be a bit long, but there are 5 parts to it, all joined together by the concatenate symbol (&):

" Times "
" = "

The variable i holds the current value of the For Loop; " Times " is just direct text; multiplier holds the value we're multiplying by (our times table); " = " is again direct text; and answer is the answer to our times table sum.

If you want to clear the items from a List box you can do this. At the top of the code, enter this line:


So instead of selecting Add from the final drop down list, select Clear.



Add another textbox to your form. This will represent the "times table". So far you have been getting this value directly from the code. For this exercise, get the multiplier value directly from the textbox. Add appropriate labels to all your textboxes.


In the next part, we'll take a closer look at the basic Maths symbols you can use in VB .NET.