NSBasicCE Tutorial

Lessons in NSBasicCE


vns_textmedium

Programming Using NSBasicCE

All content (c)1999-2007 Serg Koren and VisualNewt Software.

All rights reserved.

List of Articles:

  1. The Package and Installation.

    Discussion of the history of BASIC, and how it relates to MS VisualBasic and NSBasic. Steps needed to install NSBasic on a Casio-E105 are described.

  2. The Editor and Modes.

    A complete discussion and exploration of the NSBasic programming environment detailing every menu item. A description of Immediate and Programatic mode programming with examples.

  3. Objects, Properties, and Methods! Oh My!

    A beginner's explanation of Object-Oriented-Programming (OOP) with emphasis on NSBasic.

  4. CommandButtons.

    An explanation of how to use CommandButtons in NSBasic.

  5. MSGBOXes, SUB and FUNCTION

    What SUBroutines and FUNCTIONs are and how to use them, basic parameters, and the MSGBOX user-interface widget.

  6. CheckBox and Variables

    A discussion of variables, how they are stored in memory, how to use them, and the CheckBox widget.

  7. Strings and COMBOBOX

    We talk about what strings are, and how to use them and combine them. We also look at the ComboBox object.

  8. Dissecting Strings and the Date Object

    We follow up our discussion on strings and talk about taking them apart. We also look at the buggy and barely usable Date Object.

  9. Arrayed Things and the INPUTBOX

    This article deals with arrays, what they are, how to set them up, and use them. We also talk about the INPUTBOX and what it is good for.

  10. Decisions, the Label and ListBox

    Getting your program to decide things for itself, and how to put labels on your screen, along with the ListBox object.

  11. DejaVu Again

    Getting your program to loop, and the OptionButton object.

  12. FOR EACH, INSTR, and the PICTUREBOX object

    A powerful new kind of loop, searching for a string in a string, and graphics.
  13. PRINT, REDIM, and the TEXTBOX object

    Printing information to the screen, resizing arrays and text objects.

nsblogo2_textmedium

ARTICLE 6--CHECKBOX AND VARIABLES

Programming Using NSBasicCE

ARTICLE 6--CHECKBOX AND VARIABLES

All content (c)1999, 2002 Serg Koren.

All rights reserved.

Welcome to the sixth installment of NSBasicCE.

This time we go over another user interface widget, the CHECKBOX. We also finally talk about variables, what they are and how to use them.

Leftovers from Last Time

Last time we talked about MSGBOXes and I asked you to explain what the following nested call does:

 
MSGBOX MSGBOX("My homework!",vbYesNoCancel,"Homework "),vbOKOnly,"My MSGBOX homework"

a) How many functions are there?

b) How many subroutines are there?

c) What gets called/executed first, the subroutine, or the function?

d) When you run this line, what is that number that pops up? Run it again and try something else.

e) How many parameters does this line have?

The answers are:

a-b) Actually these are trick questions. There are no subroutine and functions in the line. There are however calls to subroutines and functions.

  1. 1. Remember that functions return values and use parentheses around their parameters in the call. So the function call is:
    MSGBOX("My homework!",vbYesNoCancel,"Homework") and it returns its value to the outer MSGBOX call:
    MSGBOX <…>,vbOKOnly,"My MSGBOX homework."
  2. 1. Remember that a subroutine call does not use parentheses around their parameters and doesn't return a value. So the subroutine call is:
    MSGBOX <….>,vbOKOnly,"My MSGBOX homework."
  3. The function. Typically things get executed first line to last line. Each line gets executed left to right. However nested calls (and as we shall see below variable assignments) get executed differently. Nested calls get executed from the innermost call (the function in this case) outward.
  4. The number that pops up is the value of the inner MSGBOX function call. The outer MSGBOX call displays it. Specifically, the number represents the value of the button that was clicked in the inner (function) MSGBOX call. You can validate this by looking up the number you get in the manual.
  5. This one depends on your point of view. You could say: 3 or 5 Basically anything separated by a comma counts as a parameter. You get the answer 3 if you consider that for the outer MSGBOX (subroutine call) the first parameter is the entire inner MSGBOX (function) call and that counts as a single parameter.

One thing which you probably discovered (and I left for you to figure out on your own) about the MSGBOX is that it's buggy. That is, if you use the MSGBOX on an HPC it works fine. However, the MSGBOX doesn't fit on the screen properly i you use it on the CasioE-105 and other PPCs. There is no way to resize the MSGBOX on the screen so that it fits. This is a Microsoft bug. The only way to use a MSGBOX on the PPCs is to write your own from scratch. I've saved you the trouble, and if you need a MSGBOX on a Casio-E105, you can use mine, which you can find at: http://www.VisualNewt.com/CE/NSB. Please note that using my MSGBOX is a bit different from the standard one. This is due to the limitations of WindowsCE and NSBasic, so make sure you read the documentation and examine the sample file on how to use my version. On to new stuff!

Variables

We've used variables in some of our example programs, and articles, but I've never really explained them. I think it's time I do so, since we'll be using them a lot from now on, and if you're a beginner to programming, an explanation is in order. If you're familiar with variables you can skip this section.

"Variables" is a somewhat misleading name. From the name you would think that variables vary something. They do, but more importantly, variables store and hold things. What things depends on the type of variable, but generally speaking variables can hold two types of things: numbers, addresses. In programming, just like in school, there are all sorts of types of numbers: integers, floating point, imaginary, etc. In most programming languages, you have to worry about what type of number gets stored in what type of variable.

That is, some types of variables can only store integers, while other types can only store floating point, etc. BASIC (and NSBasic) is more flexible; they allow you to not have to worry about the type of variable and the type of number that is stored in it. This sounds like a great idea, and it is, but as in real life there are always tradeoffs. This ease of use gives up a little in the efficiency (how fast) your program runs, and how much storage (memory) the variable uses. And really, NSBasic allows you to get the actual type and deal with it if you need to do so. But most of the time, you don't have to worry about either the type or the efficiency of your program. The other major type that a variable can store is an address. Address?

Think of your WindowsCE's memory as being a huge ruler marked in inches. The ruler is laid out on the street and goes from 0 all the way up to 8Meg (about 8 million) inches (your device may have more or less memory). Now also assume you can store exactly one object at each inch. You can't store stuff at 1.5 and you can't store 3 things at 2 inches. One object and only at an inch marker. So if I had stored a pink poodle somewhere on the ruler (albeit a tiny one), how would I tell you where to find it? The easiest way would be to tell you the inch marker the poodle was sitting on. That would be the "address" of the poodle (2105 is where I had put the poodle.) So an address is just another type of number. So your memory ruler stores numbers. One per inch marker (address) and only at exact markings. Ok so what type of addresses can NSBasic handle. Obviously not pink poodle addresses.

If you followed the above you've probably surmised that addresses must have other numbers stored at their locations. So an address can have a number. An address can have another address. So what about objects? Objects are really just represented by a whole slew of numbers (depending on the object). But we can only store one number per location, so what d we do? Well the simplest thing to do would be to take our object (made up of a lot ff numbers) and store all the numbers at sequential locations on our ruler (making sure first that there aren't any other objects in the range we need). Ok, so we've laid out our object in sequential spots on our ruler (I'll start calling our ruler "memory" now, since I thing you get the point).

We can tell our program where our object is in memory by pointing to the start of the sequence of numbers we've stored. This starting point is known as a "base address". One other piece we need to know is the end of the object, but we don't store the end of the object usually, we store the number of numbers in the object (its length). So given the base address of an object and its length (which we store in another location in memory) we can get our object. What happens if we can't find enough sequential spots for our object? We run out of memory and get an error message (or crash usually in the MS world)!

Phew! Most of this is just background info, and you really don't need to know it for programming NSBasic, but it doesn't hurt to know. In the last article we also mentioned briefly there were two types of parameters. Now we can talk about them. There are parameters which get "passed" by value. The one's we've talked about, mostly. And ones that get passed by something known as "reference". "Reference" is just another piece of computer-jargon, which means, "address". So, if a parameter is passed by reference, we don't actually pass a number, we pass the address of the number. Why do we care? Well each parameter can only hold one number, just like our memory ruler. So if we need to pass something like an object to a subroutine or function, we do so by passing its base address by reference (NSBasic knows how to figure out the length if it knows where the base address is). Another type that gets passed by reference is an array, which we'll discuss next time.

Take a break, drink some orange juice, and absorb the above.

One thing I should explain (which has nothing to do with programming, but I've run across this innumerable times), is the difference between memory, storage, RAM, ROM and hard disk space. Amazing how many people confuse these. Briefly! Memory is RAM. It's the memory used when your program runs. Storage is a generic term for where things are held when you power off the computer. This is usually hard disk space, ROM, or something called Flash RAM. RAM stands for Random Access Memory (so it's not storage, unless its "flashable"). ROM stands for Read Only Memory, and you can't write to it, so its only use is for storage. You can't run programs in ROM. Hard disk space is used only for storage. Nothing ever runs on a hard disk. Things only run in RAM. So, if someone asks you how much memory you have you should tell him/her how much RAM you have in your system (8M, 32M, 128M etc.) If they ask you how much storage (space) yo have in your system you tell them the size of your hard drive usually (100M, 2G, EEC.). Believe me this little bit will help any customer service techs you may deal with from getting frustrated, pulling their hair out, and shooting their co-employees.

Ok, now that I've gotten that out of my system (no I'm not a customer service tech), and we've described what variables do, how do we actually use them in a program? Well it's all well and good that we can use an address in memory, but it's not easy to remember that spot 3198 has the location of the number 3 stored in it, so we give our memory slots a name. What name is up to you in your program. You make up a name, and NSBasic (or whatever language you use) will decide to store anything you use with that name at a given spot in memory. So you don't even have to worry about where in memory get stored (usually) just the name you gave it. So this should tell you that you should alwaysgive your variables meaningful names. Names you can understand and that describe what the variable holds.

You can either "declare" the variable first (to declare something in programming, means to tell NSBasic that you will use this name to store something), or you can just use the variable to store something. Why would you want to declare something? You should always declare variables before you use them. This not only serves as documentation (making it clear you're going to be using this set of names as variables) but it makes your program run a bit quicker because the program can find all the space it needs to store your variables before you use them, instead of hunting for memory as it runs. It also lets you know you've run out of memory while you're still writing your program before someone runs the program you just gave them. So how do you declare, or tell the program that you intend to use a variable? You use a DIM statement. DIM is short for DIMension. DIM used to be only used to declare arrays of numbers and arrays have something known as dimensions. In old-style BASICs you had to declare or DIMension an array, but you didn't have to (actually couldn't) dimension a single number. Newer BASICs (including NSBasic) allow you to dimension both. If you look up DIM in your manual you see it looks confusing. We'll ignore the confusing bits for now, and rewrite the statement as:

DIM nameA, nameB, nameC…

So lets say we want to get the circumference of our pool if we know its radius. The formula you may remember is:

Pi * Diameter = Circumference

We would need to have to declare four variables:

Pi, Radius, Diameter and Circumference

The easiest thing to do is just use those names, so in our program we would have the lines:

DIM Pi, Radius, Diameter, Circumference

(or we can have one per line or other combinations such as:

DIM Pi, Radius
DIM Diameter, Circumference

…these are all equivalent)

Now we've told our program we're going to use these variables to store numbers. How do we actually store a number into each of these? We use an equal sign:

Pi = 3.14 ' the variable name is always the leftmost thing in the line…
Radius = 100 ' for an assignment statement.

An assignment statement (more computer jargon) just assigns something to a variable name. Now all we have to do is calculate our formula and assign its result to our Circumference variable.

Diameter = 2 * Radius ' note that the variable name that we are assigning to is on the left side again
Circumference = Pi * Diameter ' same here

From the above you can see that:

2 * Radius = Diameter

is not a valid programming command, because the variable we're trying to assign in to is on the right, instead of the left. NSBasic would try to take the value stored in Diameter and store it into whatever (2 * Radius) was, but (2 * Radius) isn't a valid variable name, so NSBasic gives you an error. Basically this means that NSBasic won't let you store a number into another number:

3 = 2

but only into variables:

MySpot = 2

Even though MySpot is actually an address of a memory spot (a number).

Another confusing thing for programming newbies is that they may be confused to lines similar to:

Diameter = Diameter + 50

Algebraically, this is of course nonsense in most cases. But this isn't algebra. Although the equal sign (=) is used, it doesn't really read as "Diameter Equals Diameter Plus 50". Instead, it should be read as "Stored into" and read from the part to the right of the equal sign: "The value stored in the variable Diameter plus 50 is 'stored into' the variable Diameter." What this does is increment the value of the variable called Diameter by 50. So if the value of the variable (I'll just say 'variable' from now on) Diameter was 20 before this line gets executed, it will be 70 afterwards.

One last thing about variables: something called scope. No, this isn't a mouthwash. Scope is more computer-jargon (sorry, but it comes with the territory). Scope is easy to grasp, but hard to explain. Think of scope as a set of brick walls (or more accurately solid fences). The fences enclose other fence enclose other fences, etc. Inside each fence there are a number of cows. If you're outside the outermost fence you can't see anything inside. If you're inside the outermost fence you can only see the cows in your fence ring. As you go deeper into the fences you learn more and more about the number of cows in each ring, and you remember the number of cows you passed as you move inward. Once you're inside the deepest fence you know the number of cows at each ring level. Now as you travel back out again, you suddenly forget how many cows are in the fence ring you just left. A fence ring is scope. But instead of cows programmatic scope learns about and forgets variable names. Now replace the fences with SUBroutines and FUNCTIONs. SUBs and FUNCTIONs inside of other SUBs and FUNCTIONs etc. Something like:

DIM A
SUB OuterFence
   DIM B
   SUB Fence1
      DIM C
      FUNCTION Fence2 
         DIM D
	SUB Fence3
            DIM E
            FUNCTION Fence4
	      DIM F
	      …
	   END FUNCTION
	   E = Fence4 ' run fence4
	END SUB
	Fence3 ' run fence3
      END FUNCTION
      C = Fence2 ' run Fence2
   END SUB
   Fence1 ' now execute Fence1
END SUB
OuterFence ' start executing
 
(Yes you can have code like this, no it's not good style!) Ok so if you're outside the outermost SUBroutine (OuterFence) the only variable you know  about is "A". As you cross into the fence you suddenly know about variables A and B. As you travel inward you until you enter Fence4 and you know about A,B,C,D,E, and F. So inside Fence4 you could have a line that  said
F = A + B + C + D + E

Now as you go back out (when FUNCTION Fence4 finishes running) you forget about variable F. So even though you could have the above line in Fence4, you can't have the above line in Fence3. Even thought you knew about the variable F before! You just forgot it! So the best you could do is:

E = A + B + C + D

As you continue to exit and forget variables until you're back at the OuterFence call, and the only variable you know about is A. That's scope! Why do you care? Well you could have something like:

DIM A
A = 1
SUB OuterFence
   DIM A
   A = 2
   MSGBOX A,vbOKOnly,"Inside OuterFence"
END SUB
MSGBOX A,vbOKOnly,"Before calling OuterFence"
OuterFence
MSGBOX A,vbOKOnly,"After calling OuterFence"
 

Yes this is possible! You can DIM variable inside of SUBs and FUNCTIONs! What happens? Outside the OuterFence you know about A = 1. Once you enter the OuterFence subroutine you know about A = 2, once you leave the OuterFence, you forget about A=2, but you still know about A = 1. Try it! This is a useful technique, but you have to be careful! More jargon! Local (or locally scoped) variables are all the variables inside of a fence. Global (or globally scoped) variables, are variables outside of all fences!

One last thing, we mentioned just using variable names. Your program could have:

A = 12 ' without a DIM A

It's always good, as I mentioned, to declare your variables, but you can forget to do so "in the heat of programming." So how do you make sure you always declare a variable? This is where another Immediate mod command comes in useful. OPTION EXPLICIT is a statement that forces you to DIM all variables before you use them. Look up OPTION EXPLICIT in the manual. Then try this short program:

OPTION EXPLICIT
DIM A
A = 1
B = A + 1
MSGBOX B

What error message do you get? If you see this message, that tells you you forgot to DIM a variable! Now remove the OPTION EXPLICIT line and try running the program again It should work fine! Now fix your program so you have the OPTION EXPLICIT and it runs without errors.

CHECKBOX

A CheckBox is another GUI widget. If you look it up in the manual, you find that it looks a lot like our friend CommandButton. You should know now how to create a CheckBox, so we'll only discuss the new properties, methods and events. Most of these you've already played with in CommandButton. The property alignment specifies whether the text caption o the button is aligned to the left, middle or right edges of the caption field you specify (if you specify a width that is just wide enough for the caption it won't make any difference). TabStop allows you to specify whether the CheckBox will be able to receive Tab characters when you hit the keyboard Tab key. There are a couple of new Font styles you can play with (you should know how by now). The other import property is the Value property. This property lets you set whether the CheckBox is checked when you create it:

ADDOBJECT "CheckBox","MyBox",20,20,30,20
MyBox.Value = TRUE ' start the checkbox checked

You can check the box using TRUE in the Value property, and unchecked using FALSE. The default is FALSE. (You can now see how we use assignment statements to assign a value (TRUE which is actually a number) to an object property variable--it's all coming together!) To see if a CheckBox is checked, you can use he code:

DIM CheckBoxState
CheckBoxState = MyBox.Value

Here we're assigning the value of the Value property to the CheckBoxState variable. The value returned is a number instead of TRUE/FALSE. The numbers are 1 = TRUE, and 0 = FALSE.

There are no new Methods to discuss with CheckBox. The only new Event is the Change Event. This event is triggered (calls your Change event handler) whenever the user toggles he CheckBox from true to false or back.

SUB MyBox_Change
   MSGBOX "Someone tapped on me!"
   MSGBOX MyBox.Value
END SUB
 

For next time here's a simple assignment (excuse the pun):

Write a program that has:

  1. A command button labeled "Count"
  2. 2 CheckBox objects labeled "Left" and "Right"

The program should:

  1. Display a message box whenever the user taps on a check box. The message should display the name of the check box being tapped.
  2. Display a message showing the total number of times the user tapped either of the checkboxes.
  3. Use a variable to keep track of the number of times the user tapped either of the checkboxes.

Next time, we'll go over Strings and text (really another form of variable), and talk about ComboBoxes!

nsblogo2

ARTICLE 3--Objects, Methods, and Properties! Oh My!

Programming Using NSBasicCE

ARTICLE 3--Objects, Methods, and Properties! Oh My!

All content (c)1999, 2002 Serg Koren.

All rights reserved.

Welcome to the third installment of NSBasic on the CasioE-105.

This time around I'll discuss some major concepts in computer programming today, namely the concepts of object-oriented programming (don't worry, I'll go slow). But first, I left off the last article with a question.

Leftovers from Last Time

Given the following code snippet (which you can enter into NSBasic...see the last two articles on how to do this).

'---start code here---

' Everything inside a SUB or FUNCTION gets done programmatically and waits to be told to run by your program.
SUB ProgrammaticMsgbox
MSGBOX "This is the programmatic one."
END SUB
' Everything outside a SUB or FUNCTION gets done immediately (as soon as you hit Run).
result = MSGBOX ("This is an immediate mode MSGBOX. Tap Yes to see a programmatic one.",vbYesNo)
IF result = vbYes THEN
	ProgrammaticMsgbox ' tell our programmatic MSGBOX to run now
END IF

'--- end code here -----

The question I asked was: Why don't you get the window with "This is The programmatic one." first? Lines in programs get executed (run) in sequence from the first (top) to last (bottom).

The answer relates directly to the last article. First thing I should mention is that any line starting with a single-quote (') is a comment, and ignored by NSBasic. It's a way of reminding you or explaining to others what your program code is actually doing. Use comments extensively in your program. I'd go as far as to say, that you should probably have more comments than code (but I won't hold you to it).

Anyway, the answer is that the MSGBOX "This is the programmatic one." doesn't show up first because it doesn't execute UNTIL the SUB (subroutine) is called (executed). Where does it get executed? It gets executed LATER in the program when the result = MSGBOX(...) line gets called. And this gets called in IMMEDIATE (see the last article) mode, but only when you tap the Yes button on the first dialog (This is an immediate mode MSGBOX. Tap Yes to see a programmatic one.)

So in short Immediate mode commands get executed right away. Programmatic mode commands (those in SUB or FUNCTION) only get executed when called.

This leads to the ultimate conclusion that all NSBasic programs ultimately get run from an Immediate mode command somewhere in the program. I'll give you a general guideline to better programming:

The better (more organized) your NSBasic program is, the fewer Immediate mode commands it has in it.

You can't get away from Immediate mode commands, but you should only use them when you have no other way to go. We'll talk more about this next time, but now some more concepts and some more code!

Object-Oriented-Programming: Object, Methods, Properties, Events

Object-Oriented-Programming (OOP for short) is the way to go nowadays. It's the big thing. It's a way of thinking about programming. The little bit of code we've seen so far has not been OOP. The stuff we've seen is called "procedural programming" (sorry no acronym for this). It's procedural because it has procedures (also known as SUBroutines and FUNCTIONs). The code gets executed line by line from the top down (with sidetracks as SUBs and FUNCTIONs are called). It's procedural because you're basically doing instructions to get, massage, and output data by issuing commands.

OOP thinks differently. Instead of thinking about data and what you do with it, for something to happen, you think about objects (real such as cars, loaves of bread, etc., and psuedo-objects such as arrays, lists, and even numbers.). In OOP you define objects that represent real (and not so real) things in the world. Each object you define knows how to do what the object does. A car object would know how to speed up, slow down, turn, brake, stop, etc. How does it know? Once you define an object (car) you define the things the car object knows (speed up, slow down, brake, etc.). These "things" the object knows how to do are called methods. So Objects have Methods which are things that Objects know how to do. In other words, you wouldn't have a Method in a car Object called "MakeToast", because a car doesn't know how to make toast (usually)--a Toast Object would have a Method called MakeToast. How many Objects can you have? As many as you need. How many Methods can an Object have? As many as your Object needs. Ok. So we have a car Object and it knows how to speed up using a SpeedUp Method. How fast is the car going? How does the car Object know? Via a Property. Properties are characteristics of the Object. A car Object would have a Speed Property; it would probably also have an Acceleration Property that told it how fast the SpeedUp property was accelerating the car. A car Object would also have Make, Model, Color, Year properties. Any characteristic that the car Object would have to worry about and use. If the car Object didn't care what Color it was, you'd leave out the Color Property.

So, in OOP you design (or in NSBasic you use) Objects, that have Methods that makes the Object do things, and Properties that tell you things about what the Object is doing at that instant (the Speed may be one thing--30mph now--but may be 105mph later.) Ok. There are two more OOP concepts we need to worry about (there are lots more things to know about OOP, but this is really all you need for NSBasic. How do we tell an Object it should do something? We send the Object a Message. For example, to tell our Car Object that we want it to speed up, we might send a "speedup" Message to the Car Object. The Car Object knows that this means it should call the SpeedUp Method which really does the work of speeding the car up. The last concept is one of Events. An Event can be thought of as a trigger that causes the Object to do something. In our example, the Car Object receiving a "speedup" Message is an Event. The Car Object speeding up, may or not be an Event depending on how it is written. Another type of Event is one caused by the user of the program (you). Tapping on something, typing something, dragging something, are examples of user-generated events. Typically, you have to tell (write code) to tell the Object what to do when the user generates an event.

Phew!

So: Object--->knows how to do something which are Methods

Object--->has characteristics which are Properties

Object--->get sent Messages which cause Methods to execute

Objects-->react to Events (receipt of Messages or user caused events)

That's a lot of info to digest but it isn't too hard to understand. Just a lot of jargon.

You may be wondering now....Why oh why do I have to worry about this stuff? Why can't I just program using NSBasic like we have been? Well to be honest you could, but your programs would really be very primitive and crappy looking. The fun stuff is all done using OOP. The fun stuff in this case being the user-interface (GUI--buttons, menus, edit fields, calendars, databases, etc.)

To take a more concrete NSBasic example, get your NSBasic Bible out (the manual) and turn to the ListBox page. The title on the page has the word Object on the right. This tells you this page describes an OOP Object. (If its a SUBroutine or FUNCTION, it will have SUB or FUNCTION; you will also find STATEMENT which is a simple command in NSBasic, and OPERATOR which is part of a statement.). Ok, a ListBox in NSBasic is an Object, which means it has Properties, Methods and Events. These are all listed at the bottom of the page. A ListBox has Properties named: BackColor, Bottom, FontBold, etc. Properties are characteristics. They determine what your ListBox looks like. You can set these or you can look at them to find out what your ListBox looks like. Methods supported by a ListBox include Hide among others. So our ListBox Object knows how to Hide itself (make itself invisible). Events of a ListBox include Change, Click, DblClick, and GotFocus. Hm...no Hide event, no MakeInvisible event. Why? Because typically, the ListBox doesn't disappear as soon as a person clicks on it. That's a key there! "Clicks on it" So how do we get a ListBox to hide itself? Well we use the Hide Method, by sending the ListBox a Hide message. How do we send messages? We use the name of the Object a dot (period) and then the name of the Method we want to have the Object execute. So, to send a Hide message to a ListBox we would write:

ListBox.Hide

and the ListBox would disappear. We can use the Visible Property to see if it is hidden or not similarly:

... ListBox.Visible ....

The ... indicates other code we aren't going over right now.

Extending this, how do we get a ListBox object to disappear when we double-click on it? Well we use the DblClick Event to send our ListBox.Hide Message.

Events are defined as SUBroutines in NSBasic and instead of the period we use an underscore (_) (I'm not sure why). So our code looks like:

SUB ListBox_DblClick ' respond to a user clicking on our ListBox
ListBox.Hide ' hide the listbox by sending it a Hide Message which executes the Hide Method.
END SUB ' always need an END SUB (or END FUNCTION for a FUNCTION)
 

Cool huh? One thing we bypassed (deliberately) is how to make a ListBox Object. Your program can have hundreds (well tens) of ListBoxes, how do we know which one we want to hide? Well when we create one, we give it a Name. An Object has a Name (which is really a Property). So if we have 2 Car Objects one may be Ted's Taurs, and the other Tom's Taurus. We create an Object in NSBasic using the ADDOBJECT command as listed at the top of the page in the manual. For a ListBox it is:

ADDOBJECT "ListBox",name,xpos,ypos,width,height

"ListBox" is the type of Object we want to create.

'name' is something you provide as the Name for your ListBox. Names in NSBasic have to be strings (enclosed in double-quotes ").

xpos,ypos are the x and y coordinates of where the ListBox will be (Properties) as are the width and height of the ListBox.

Here's your first complete NSBasic program (simple though it is):

'---start code here---
'
' A simple program that creates a ListBox and lets us show and hide it by clicking on it
'
' A subroutine to create a ListBox on the screen
SUB MakeAListBox
	ADDOBJECT "ListBox","MyListBox",50,50,100,100 ' create an empty ListBox
END SUB
 
' A SUB to handle a DblClick Event (a Click event handler) for the ListBox called "MyListBox"
SUB MyListBox_DblClick
	MyListBox.Hide ' Hide MyListBox
END SUB
 
' Our main routine where the main things happen...good to always have one
SUB Main
	MakeAListBox ' create a ListBox
END SUB
 
Main ' our one and only Immediate command for this program to run the Main SUB
'---end code here---

Simple huh? If you can follow the above program, you've gone through the most difficult concepts in NSBasic. Everything else is just learning the individual Objects, and commands (Statements). Browse the manual and look at the Objects (upper right title) and look at the Properties, Methods and Events each type of object supports (many are similar).

Simple quiz for next time. Write a short program (like above), but include a CommandButton Object. The program should have:

1) A ListBox

2) A CommandButton

The program should:

1) Hide the ListBox when you double-click it.

2) Unhide (use the Show method) the ListBox when you tap (Click) the CommandButton.

We'll show you one version of the code (and a simpler version) next time. Next time, we get into real programming and fewer concepts! Stay tuned!

Cheers!

nsblogo2

ARTICLE 9 -- ARRAYED THINGS AND INPUTBOX

Programming Using NSBasicCE


ARTICLE 9 -- ARRAYED THINGS AND INPUTBOX

All content (c)1999 Serg Koren.
All rights reserved.


Welcome to the ninth installment of NSBasicCE.
Here we discuss arrays, and the INPUTBOX widget.

Leftovers from Last Time


In our last article we discussed how to take a string and extract substrings from it. I then asked you to write a simple app that has:

  1. a date object
  2. a command button

It should:


  1. Save the date the user taps on in a variable called TheDate
  2. Display the message: "This is the i-th day of the j-th month." whenever the user taps the command button.

Note that i and j above are numbers you can get from TheDate.
Here is my solution:

       '--------begin code here--------------
       '
       ' Aricle 8 exercize
       '
       '
       '---------- Create our objects routines
       OPTION EXPLICIT ' force DIMensions
       DIM FullDate ' global variable to store the date string returned by Date        object
       DIM Day ' the part of the date string containing the Day (i-th day)
       DIM Month ' the part of the date string containing the Month (j-th month)
		
       ' Create a date object
       SUB CreateMyDateObject
       	  ADDOBJECT "Date","MyDateObject",10,10,100,30
       END SUB
	
       ' Create our command button
       SUB CreateMyCommandButton
       	  ADDOBJECT "CommandButton","MyCommandButton",10,50,100,30
       END SUB
	
       '----------- Set up our event handlers
       ' Date object event handler
       SUB MyDateObject_Change
          FullDate = MyDateObject.Text ' get the selected date and store it in our variable
       END SUB
		
       ' CommandButton event handler
       SUB MyCommandButton_click
         Day = MID(FullDate,4,2) ' extract the dd portion of mm/dd/yyyy
       	 Month = LEFT(FullDate,2) ' extract the mm portion of mm/dd/yyyy
       	 MSGBOX "This is the " & Day & "th day of the "        & Month & "th month."
       END SUB
	
       '------------- Our setup routines
       SUB SetupUI
       	  CreateMyDateObject
       	  CreateMyCommandButton
       END SUB
	
       SUB Main
       	  SetupUI
       END SUB
       	
       Main ' our IMMEDIATE command to get things running
       '--------- end code here


That's basically it. However, you'll notice that if you choose the 1st day or month, your message is grammatically incorrect! You don't know enough at this point to fix it, but you will next time!


ARRAYS

Simply put, arrays are collections of things. In programming, arrays are  a powerful tool that lets you simplify your code by grouping collections of variables together under one name. An example would be the best way to understand this. For instance, assume you have to program a game having ten boxes and you need to put something into the third. You could set up variables for each box thusly:
     
DIM Box1
DIM Box2
DIM Box3
       ...
DIM Box10
Box3 = Something
     


This would work fine, but it's a lot of typing isn't it? Wouldn't it be simpler saying "here is a bunch of boxes, and I want the 3rd one."? In NSBasic you can do this by creating an array of variables and giving them a single name. In this example lets call our collection of boxes "Box". We specify the maximum number of things (boxes) in our collection by putting the number inside parentheses after the name in our DIMension statement! So if we want to have 10 boxes we would have a DIM statement:

DIM Box(10)


Now if you're just getting into programming and have been following these articles you may be thinking..."doesn't the parentheses mean that this is a function?" Well not in this case. You don't have the FUNCTION keyword. But actually in some languages (Smalltalk, etc.) This indeed would be a function-like object. But in NSBasic, this is just how you specify an array of variables. Ok, so back to our example...how do we put stuff into our third box?

 Box(3) = Something


Easy! So how do we see what is in the third box instead? Just as you would expect...

X = Box(3)


And likewise you can do things like...

Box(3) = Box(3) * 2
     

...which would multiply the value in array element 3 by 2. No, the number isn't 6. It depends on what is stored in Box(3). If we did:

Box(3) = 12
Box(3) = Box(3) * 2
     

...then Box(3) = 24! Can we do...

Box = Box(3) + 2
     
...no! You can't do something to the entire array. You have to specify which element in the array you want to operate on (again this is a limitation  of NSBasic, since other languages allow you to operate on the array as a whole).
       
So far we've been assuming arrays hold numbers, but arrays can hold any data type!
     
Box(4) = "Hello"
Box(5) = "There"
Box(6) = 12 * 2
        
MSGBOX Box(4) & Box(5) & " array element 6 has " & Box(6) & " in it."
     

You can't however put objects into arrays!

Box(7) = MyDateObject ' a Date object you create elsewhere
     

will give you a runtime error (an error that you get when you run the program) of "Object doesn't support this property or method." However, there are ways of creating arrays of objects (which we'll talk about in a future article.)


A couple of important things to note about arrays. The first element in the array is actually element 0! That means that in our box example our boxes are numbered 0 through 10, an d not 1 through 10! So what happens when we try:

Box(11) = 1
        

Try it!

Can we get the 3rd through the 5th box in our array? No, again you need to deal with each element in an array singly.

Arrays are very straightforward once you get past knowing how to DIM and reference (use) them. However, we've only been discussing one-dimensional arrays. That is arrays of things we can line up in a single line. But lets say you need to program a Bingo game board for your Auntie Ethel who is addicted to bingo! A bingo board consists of a two-dimensional array (a grid) Or a spreadsheet? In this case we use a two-dimensional array set up by a DIM statement that specifies the maximum number of elements in each axis (vertically and horizontally). So if we are building a mini-spreadsheet that has 10 rows and 30 columns we would use the DIMension statement:

DIM Sheet(10,30)
     

or

DIM Sheet(30,10)
        

Huh??? Well programming languages don't know anything about the concepts of "vertical" and "horizontal", so the order in which you declare them in the DIM statement is totally arbitrary. By convention, however we tend to think of row-column instead of column-row, so the first is more accepted. However, you can use the second and it will work fine, but you personally as the programmer have to remember which is the row and which is the column. So it's a good idea to put in a comment to remind you...

DIM Sheet (30,10) ' column, row
     
or better yet....
DIM MaxRow
DIM MaxColumn
MaxRow = 10
MaxColumn = 30
DIM Sheet (MaxColumn,MaxRow)


We explained before why this version is better programming style, although the single DIM statement is faster to type.

Also, note that in the above example we didn't DIM Sheet(29,9) (because of the 0th element in each dimension). This wastes a bit of space, but usually isn't critical, and it simplifies our programs so that we don't have to subtract one each time. You may be scratching your head here again...say we want to load cell 5,3 with a 2 if we had DIMmed the array as

DIM Sheet(29,9) ' because our sheet starts at Sheet(0,0) and not Sheet(1,1)
Sheet(4,2) = 2 ' would actually be cell (5,3) because our array starts at Sheet(0,0) and goes to (29,9)


but because we dimensioned

DIM Sheet(30,10) ' and not use cell (0,0) for anything
Sheet(5,3) = 2 ' is easier to deal with although it's actually (6,4), but we just ignore the (0,0) element to simplify our lives
        


Read that through a couple of times so you understand it. Draw it out on some graph paper too if you need to. It's not hard to understand, just a bit clumsy to explain.
That's basically it for arrays. Oh, how many dimensions can an array in NSBasic have? We've only discussed two. NSBasic arrays can have up to 60! dimensions. So you could have a DIM statement:

DIM Wow(20,340,1,40,...bunch more...,3) ' for 60 dimensions separated by commas
     

Don't ask why you would ever want to deal with this...

INPUTBOX


So far we've been dealing with programs that don't let the user type something in. The INPUTBOX is a widget that lets you do just that! It's similar to MSGBOX in that it displays a separate mini-window and display a message. It's different in that the window it displays also has a single text field that lets the user type something in. Refer to the manual page on INPUTBOX.

INPUTBOX (prompt[,title[,default[,xpox,ypos]]])
        

As you can see INPUTBOX is a function and it returns whatever string the user typed in. As you can also see from the manual, the only required parameter is the prompt. The prompt is the message to display to the user. The INPUTBOX is very easy to use. You don't have to create it or set up event handlers, you just use it.

A = INPUTBOX ("Type something please","My Input Box Title","Gee I can preload an answer",10,10)
     

Try that. The "default" parameter (the 3rd one), lets you set a default string in the input field to save the user some typing.

B = INPUTBOX ("What is your name?","My Name Input","enter your name here",10,10)
     

or it can be used to tell your user where to input stuff. (Yes I've seen this done, and I assume its for the computer-challenged among us, but I think this is bad design. Just leave it out!)
There is one really important thing you'll soon discover if you try to use INPUTBOX on a CasioE-105 and other PPC handhelds. INPUTBOX doesn't scale properly to the size of the screen. It doesn't fit! This is a Microsoft bug! To get around this problem, you can use the replacement INPUBOX routine I've written in NSBasic, and can be found at http://www.VisualNewt.com/CE/NSB/ Make sure you read the accompanying documentation, since it works a little differently from the normal INPUTBOX.


For Next Time

Write a simple program that uses arrays. The program should have:


  1. 3 CommandButtons labeled "A","B", and "C&quotl
  2. A CommandButton labeled "Do it!"

The program should:

  1. Tally the numbers of times each of the three CommandButtons has been tapped. (Hint: This is what the array is for).
  2. Prompt the user for his name when he taps the "Do it!" button, and then display a message in the format:
"Hi , you've tapped button A x times, B y times, and button C z times."



That's it for this week. Next week we'll get into a very powerful programming concept. We'll discuss how your programs can make decisions and repeat things over and over and over and over and... And our widgets of the week will be the Label, and the ListBox. We're doing two because there's not a lot to the label. See you then!


If you get stuck or have a question about anything we've gone over, feel free to e-mail me at Serg@VisualNewt.com

Cheers!






ARTICLE 2--The Editor and Modes

Programming Using NSBasicCE

ARTICLE 2--The Editor and Modes

All content (c)1999, 2002 Serg Koren.

All rights reserved.

Welcome to the second installment of NSBasic on the CasioE-105. If you're joining us late you may want to peruse the Introduction if you haven't done so already and the archived article at: http://www.VisualNewt.com/CE/NSB/AvantGo/Archives

This time around I'll discuss the NSBasic editor, the modes that NSBasic works in and some introductory material on Objects. In addition we'll do some fairly basic (excuse the pun) programming. Most people tend to jump into programming with a full blown example program and dissect it to explain how to program. I'm going to take the bottom up approach and start simple and work our way up so that I don't lose anyone along the way. You can't build a house from the top down, so we're going to lay a good foundation first.

The NSBasic Editor

If you haven't done so, you want to install NSBasic (see the first article) and start it (Start/Programs/Basic). The program that runs is the NSBasic Editor. This is where you will spend most of your time writing and developing your programs. It has the principle features of most editors, but in addition it has features specific to running and debugging your programs. Debugging, I'm sure you probably know, means finding problems in your program and fixing them. We'll have a whole article or two on debugging.

Let's go through the editor and describe its features. Along the top is the menubar with all the functionality and commands available to you. The large blank spot is where you can 'type' your programs. The menubar has some familiar features under the File and Edit menus; I'll only describe the things specific to NSBasic.

Under the File menu, there is an item labeled Encryption ON or Encryption OFF. This is a toggle menu and it switches between the two based on the source code you happen to be editing. You can also manually toggle it. Try it. What this menu does is save your program in either an encrypted or normal (Encryption OFF) format. If Encryption is OFF, then anyone can see and read and understand your source code (your program's commands). This is useful if you want to distribute your program on the Internet and you want people to see how you wrote your program. If Encryption is ON, then if you distribute your program on the Internet, then people will only be able to run your program. They won't be able to see your source code, or see how you actually did things. You on the other hand, will always be able to see your own programs no matter how they are saved (Encryption ON or OFF). The menu not only tells NSBasic how to save a program, but also reminds you how a program was saved by you when you Open it in the editor. So if you saved a program with Encryption ON, so people won't see your source code, and you go into the Editor and open the source file, Encryption will be set to ON. (You can switch it to OFF if you want to let people see the source code, or vice-versa). Try tapping a few characters into the editor and saving the file with Encryption ON and save another copy with Encryption OFF. Now quit the editor and restart it. Using the File/Open menu open each of the two files you saved and look at the Encryption menu. One should be ON and the other OFF. You can try switching the settings and resaving the files, and then reopening them to see the effect. It's fairly simple. The thing to remmeber is that the person who wrote the program always get to see the source code on their own machine, no matter how they saved it.

Ok, under the Edit menu there are two unfamiliar items: Goto Line, and Overview. GotoLine brings up a prompt and lets you enter a line number. The editor will then move the cursor to that line number. This is useful if you get an error and the error gives you the line number where the error occurred. You can use this feature to jump right to it. Overview is similar to Goto Line in that it lets you jump to a given spot in the program. Instead of jumping to a line number, however, it lets you jump to either a subroutine or function name. Subroutines and functions are "chuncks" of programs that are given names. The names identify and let you reuse a "chunk" from more than one spot in the program. We'll go over this later, but for now you can see how this feature works. Using File/Open, open one of the sample programs that come with NSBasic. Then use the Edit/Overview menu item. Depending on how big the program is, you should get a list of subroutines and functions in a second or two. You can scroll through this list (if the program is long enough). If you don't get a list, then the program you selected has no subroutines or functions. Just open another sample until you find one that has these. Once you have a list up, select one of the items in the list and tap the Goto Line button (which really should say "Go to routine") The program will automatically scroll the editor and select the line with the name you selected. The Overview feature lets you jump to places by name and is useful for long(er) programs.

The Tools menu has a lot of powerful features, so we'll take them one by one.

Format: The Format menu item tries to clean up your program's formatting. It lines things up and adds spaces where it thinks they are needed and basically "beautifies" your program's source code so its easier to read. It's not perfect and some people don't like how it does it (everyone has their own "style" of writing code...some people like lots of spaces, others don't...some like all capital letters, others don't.). But Format does a decent job. Its a good idea to run Format after you've written a lot of code, since formatting the code can sometimes show you were you might have a problem, if things aren't lined up the way you would expect. We'll talk about style later.

Run: This has a couple of submenus: Run, Execute Function, Trace, and Step. You'll use Run most often; it tells NSBasic that you want to try to run (execute) the source code you have in the editor. Try this: File/New to get a clean edit window, and then Tools/Run/Run . What happened? Your menu seems to have disappeared. Actually, it hasn't. You've told NSBasic to run your program, but you don't have one. Actually, you do, but it doesn't have any lines. NSBasic by default, creates a new blank window with a close box for every program. This blank window is where you will put all those keen (sorry for the word) features such as checkboxes, menus, pictures, fields, buttons, etc. that you find in programs. This is the window that contains them. Right now you can't do much with your empty window except close it via the close box in the upper right. So, close it, and you'll get your NSBasic editor back. So, if you're just starting out, and you mysteriously lose your menubar while in NSBasic, don't panic. Just close the window and you'll get back to NSBasic and your program.

Execute Function is disabled. This is a debugging feature. Once your program is running there are ways to interrupt it and tel it to stop where it is. You can then switch back to NSBasic (using the a task manager you can download from various sites) on the taskbar at the bottom of the Casio screen. At this point, Execute Function will be active. You can choose it to specify a subroutine or function name (like the Overview), but instead of jumping there, NSBasic will try to run that "chunk" of program as if it were a mini-program. This is useful for seeing if a given subroutine or function (I'll stop using chunk, since I think you know what it means by now), is working properly. Programs get complicated fast, and the more subroutines and functions you can break your progam up into, the easier it is to find problems and keep from writing the same code over and over and over again. Think small. A good rule of thumb on the Casio is that your subroutines and functions probably shouldn't be longer than one screenfull of source code. Next!

Trace: Trace is another debugging feature. It shows you which line NSBasic is running as its running it. Two warnings with Trace. It slows the program down a lot, and it has a problem. Any program that has a line "OPTION EXPLICIT" will cause Trace to display an error message. You can temporarily comment out (remove) the OPTION EXPLICIT line and try again (don't forget to uncomment (put back in) the OPTION EXPLICIT line when done. Try this with the Benchmark sample in the Samples folder. Trace displays the line number, and the actual source code on that line as it executes it. Compare the results by using the Tools/Run/Run item with the Tools/Run/Trace item. Why is Trace useful? If your program is going somewhere and you think its should be going somewhere else, Trace can help you find where its going wrong.

Step is a more powerful (but slower) version of Trace. It has the same problem with OPTION EXPLICIT as Trace does. Step lets you stop after NSBasic executes a line and see what it did. Try it with the benchmark program (remove the OPTION EXPLICIT again). Once you do a Tools/Run/Step you should get a window with Line 1 at the top, the actual line being executed right under that, a big empty field on the left and two buttons, Execute and Continue on the right. The line number and the line are about to be executed; that means, NSBasic hasn't actually run the line yet. Try hitting the Continue button. The window should now display Line 2. Tap the Continue button a couple of times. You can step through the entire program this way to localize where a line has gone wrong. The big input field lets you type in a temporary NSBasic command and run it with the Execute button. This is useful for trying a simple fix to a line you've discovered is wrong, or for displaying the contents of a variable (a value) to see if your program computed it properly. Unfortunately, Step doesn't let you quit easily. There should be an Abort button. To get out of Step mode and return to the NSBasic editor, type the word BYE into the empty field on the left and hit the Execute button.

Those are the Run submenus. They let you run your program, as well as to help you debug it.

The next menu item on the Tools menu is Execute Code. This feature lets you try a little bit of NSBasic code without actually putting it into your program. This is useful for trying something out before putting it into a function or subroutine if you aren't sure it will do what you think it should do. Try this to see how it works: Tools/Execute Code to bring up a mini-editor. Type in the line:

MSGBOX "I'm learning to use the NSBasic editor."

Double-check the typing and quotes, and exeucte it. But there is no button to execute it, is there? Well what happens when you close the mini-editor, using the Ok box in the upper-right? It runs the code in the mini-editor. If you get an error message, simply close the error window, close the main window (the empty one usually) and then do Tools/Execute Code again. One nice thing about this feature is that once you close the window, your test code in the mini-editor is still there so you don't have to keep typing it in from scratch. Fix your typos and try again. So, Execute Code lets you try snippets of code before you actually put it into your main program. One problem with Execute Code is that once you have the code working in the mini-editor there is no easy way to transfer (copy/paste) it into the main editor. You have to retype it in by hand.

Show Variable on the Tools menu is another debugging feature and is only active while you are running your program. Once you've interrupted your program, Show Variable is active and brings up a window where you can type a variable name and display its value (contents).

Tools/Stats just gives you how many lines your program is and how much space it takes up on your Casio. Load in a sample program and select Tools/Stats. The word "script" in the message maybe confusing to you. A scripti s a set of commands to be executed, so in that sense NSBasic is a scripting language. There are other meanings of the word "script" in computing, but we won't go there just now.

The VisualDesigner item under the Tools menu is a fairly new addition to NSBasic and deserves several articles on its own. The VisualDesigner lets you design the GUI (checkboxes, menus,etc) for your program without having to write much code. But since we're trying to work from the bottom-up, we'll leave the VisualDesigner for future articles.

That's basically the NSBasic editor. The only other feature you should be aware of at this stage is the arrow button on the menubar. This is a shortcut for Tools/Run/Run. Pressing this button will start your program executing.

NSBasic Modes of Execution

Modes of execution refers to ways in which something gets done. This relates to the word "scripting" we mentioned above, and deferred until now. First some explanations and definitions.

NSBasic is an interpreted language. The other major type of language is compiled. An interpreted language is one that is read and executed line by line. You write a program with lots of lines in it. Each line is a comand. The interpreter takes that line and translates it into an intermediate language. When you run the program, the interpreter then translates the intermediate language into its effects (what you want the line to do). A compiled language is one where all of the program lines are "compiled" or translated into a form the machine it is running on understands. You don't need a program to interpret the program. This means two things for you as an aspiring NSBasic programmer. NBasic is interepreted, so any program you distribute over the Internet or to your friends needs something to interpret the program to run. This is provided in the NSBasic "runtime" module. This is a program that knows enough to run a program that's already written, but isn't powerful enough to let someone write a program. So, if you distribute a program, the person running it either has to have a copy of (a) NSBasic, or (b) the runtime module. (It doesn't hurt if he has both). The second thing this implies is that interpreted programs are a bit slower when they run than compiled ones. This isn't critical usually, but if you're trying to write a program that has to be as fast as possible, then NSBasic isn't the way to go.

What does this have to do with modes? Well because NSBasic is interpreted, it really has two modes of operation: immediate and programmatic. Immediate is just what it sounds like. You enter a line of code and execute it immediately. The programmatic mode gets run when the person runs the program. This is a very fine distinction, but an important one. Usually it doesn't matter, but in some programs it does. For instance, if you were to write a program with no functions or subroutines, your entire program would be running in immediate mode whenever you ran it. Anything in a subroutine or a function runs in programmatic mode. Another way to look at this is whenever you use an immediate command (one not in a subroutine or function), it gets executed right away and is really useful if you want to tell NSBasic something (as opposed to having your program do something). This is another definition of "scripting"; you're telling your programming enviornment (NSBasic in this case) to do something, instead having your program do what your program does. You'll find, as we go on, that some commands in NSBasic are for use in Immediate mode, while most are useful programmatically. For example the OPTION EXPLICIT command we'll see later is a command to NSBasic to force you to do certain things when you program, instead of when you run the program its found in. So what about our MSGBOX program? The way we were using it it's an immediate command (it's not in a subroutine or function), and is really telling NSBasic to display a window. However, you can (and will) use MSGBOX inside of functions and subroutines. That way, it would run programmatically, to tell your program to display the window. Yes it's a fine line, and one you can usually ignore. Just remember that some commands are only useful outside of subroutines and functions. Another term for immediate mode is command level or interpreter level mode.

A Bit of Code

Ok, we promised a bit of code. This example shows you the difference between immediate and programmatic mode. We won't explain it, but will say that the second window is programmatic, while the first is immediate. Start up NSBasic, and type the following program in. Save it (and call it whatever you would like). Then tap the right arrow on the menubar or execute a Tools/Run/Run command. Again if you have an error message come up, double-check for typos (careful to use double-quotes). Tap Yes to see the programmatic MSGBOX. What happens when you tap No instead in the first window?

' Everything inside a SUB or FUNCTION gets done programmatically and waits to be told to run by your program.
SUB ProgrammaticMsgbox
MSGBOX "This is the programmatic one."
END SUB
' Everything outside a SUB or FUNCTION gets done immediately (as soon as you hit Run).
result = MSGBOX ("This is an immediate mode MSGBOX. Tap Yes to see a programmatic one.",vbYesNo)
IF result = vbYes THEN
	ProgrammaticMsgbox ' tell our programmatic MSGBOX to run now
END IF

Ok, a question to think about regarding this simple program. Why don't you get the window with "This is The programmatic one." first? Lines in programs get executed (run) in sequence from the first (top) to last (bottom). We'll answer this question and discuss the above program next time, along with actually getting into more programming, now that we've gone over the Editor.

Cheers!

nsblogo2

ARTICLE 12--FOR EACH, INSTR, AND THE PICTUREBOX OBJECT

Programming Using NSBasicCE


ARTICLE 12--FOR EACH, INSTR, AND THE PICTUREBOX OBJECT

All content (c)1999 Serg Koren.
All rights reserved.



 

Welcome to the "dozenth" installment of NSBasicCE.
This time around we discuss the "EACH" version of the FOR NEXT loop, the PRINT statement and the PictureBox object.
 
Leftovers from Last Time
 

Last time around we talked about getting loops and asked you to modify the answer to the last problem to use loops. Here is the code from last time that you had to start with:

'-------------code starts here

'

' Article 10

'

OPTION EXPLICIT

DIM Colors(7)

' our color array

'-------------- create our UI

' create a listbox

SUB CreateMyListbox

ADDOBJECT "ListBox","MyListBox",120,10,100,120 ' leave room for label

' load the colors into the listbox...assumes you've set up the array first

MyListBox.AddItem Colors(1)

MyListBox.AddItem Colors(2)

MyListBox.AddItem Colors(3)

MyListBox.AddItem Colors(4)

MyListBox.AddItem Colors(5)

MyListBox.AddItem Colors(6)

MyListBox.AddItem Colors(7)

END SUB

' create a label

SUB CreateMyLabel

ADDOBJECT "Label","MyLabel",35,5,80,20 ' to the right of the listbox

MyLabel.Caption = "Colors"

END SUB

' create our Remove commandbutton

SUB CreateRemoveCommandButton

ADDOBJECT "CommandButton","Remove",10,35,100,20

Remove.Caption = "Remove"

END SUB

' create our Add commandbutton

SUB CreateAddCommandButton

ADDOBJECT "CommandButton","Add",10,65,100,20

Add.Caption = "Add"

END SUB

' create FindMissing commandbutton

SUB CreateFindMissingCommandButton

ADDOBJECT "CommandButton","FindMissing",10,95,100,20

FindMissing.Caption = "Find Missing"

END SUB

' create FindDuplicates commandbutton

SUB CreateFindDuplicatesCommandButton

ADDOBJECT "CommandButton","FindDuplicates",10,125,100,20

FindDuplicates.Caption = "Find Duplicates"

END SUB

'----------------event handlers

' Our Remove handler

SUB Remove_click

' remove the selected listbox item

MyListBox.RemoveItem MyListBox.ListIndex

' MyListBox.ListIndex returns the number (array index) of the selected item

END SUB

' Our Add handler

SUB Add_click

' add the selected listbox item to the end of the listbox list

MyListBox.AddItem MyListBox.List(MyListBox.ListIndex)

' MyListBox.List( ) returns the text in the list

END SUB

' Find missing event handler

SUB FindMissing_click

' you probably got stuck trying to figure out how to do this... don't worry this was a trick problem.

END SUB

' Find duplicates event handler

SUB FindDuplicates_click

' you probably got stuck trying to figure out how to do this... don't worry this was a trick problem.

END SUB

'----------------main routines here

' set up our color array

SUB SETUPCOLORS

Colors(1) = "Red"

Colors(2) = "Orange"

Colors(3) = "Yellow"

Colors(4) = "Green"

Colors(5) = "Blue"

Colors(6) = "Indigo"

Colors(7) = "Violet"

END SUB

' set up our user interface

SUB SETUPUI

CreateMyListBox

CreateRemoveCommandButton

CreateAddCommandButton

CreateFindMissingCommandButton

CreateFindDuplicatesCommandButton

END SUB

SUB INITIALIZE

SETUPCOLORS ' this has to be done first because its used by CreateMyListBox

SETUPUI

END SUB

SUB MAIN

INITIALIZE

END SUB

MAIN ' our normal kickstart

'-------------code ends here

A hint that you need a loop are sequences of lines that are identical apart from the index into an array. In this example there are two subroutines that are ripe for loops: CreateMyListBox and SETUPCOLORS.
For CreateMyListBox replace the existing one with:

     ' create a listbox
     SUB CreateMyListbox   
       DIM I ' our index for our FOR loop
       ADDOBJECT "ListBox","MyListBox",120,10,100,120 ' leave        room for label
       ' load the colors into the listbox...assumes you've set up the array first
       FOR I = 1 TO 7 ' loop through all of our colors
       MyListBox.AddItem Colors(I) ' add a row with the proper color
       NEXT I
     END SUB    

SETUPCOLORS is harder to figure out. That is because we need to figure out how to get the hardcoded colors into an indexable list. But it seems by hardcoding it we already have, so do we need to put it into a loop?
No, not really. The existing code is good enough for most purposes. Personally, (a style thing) I still don't like the fact that the colors are actually hidden somewhere in the code, which makes it harder to find if say we want to add a color "Gray" for instance.
What I would do is extract the actual colors into a global string:

     DIM MasterColors
     DIM MaxColors
     MaxColors = 7 'number of colors
     MasterColors = "Red,Orange,Yellow,Green,Blue,Indigo,Violet," ' note the comma at the end...we need this


and then in the SETUPCOLORS subroutine I'd pull the appropriate substring out and assign it to the array. But to do this we need to know about another string function. We talked earlier about LEFT, RIGHT, and MID, now we need to learn about something called:

INSTR and INSTRREV

INSTR and INSTRREV are often used in combination with LEFT, RIGHT, and MID. INSTR lets you find where a certain substring starts, starting from the left end, INSTRREV does the same, but starts from the right end of the string (last character). How do they find a substring?
If you refer to the manual you see, that INSTR and INSTRREV are functions that are called using:
INSTR([start],<main string>,<delimiter)
[start] is an optional chaaracter position where to start searcing (say start at character 3). <main string> is the string we are searching through (in our case MasterColors), and <delimiter> is a string that we are looking for.
For example, the following code:

     DIM A
     DIM I
     A = "ABCDEFABCDEF"
     I = INSTR(A,"B") ' assume [start] is 0, find B
     MSGBOX I
     I = INSTR(I+1,"B") ' find the next occurance of B
     MSGBOX I


would return 2, and 8 In our assignment, MasterColors has colors separated by commas, so "," would be a natural delimiter. So to find the end of a string we search for a comma. That's why we need the comma at the end in MasterColors, it makes finding the last element easier. How do we find the start of the next string? It's the location of the last comma plus one.
So our code becomes:

SUB SETUPCOLORS
     DIM I ' Index into our array and FOR loop
     DIM J ' Index into our MasterColors string
     DIM J1 ' last occurance of a comma
     DIM TempColor ' a string that holds an actual color once we parse it from MasterColors
     J = 0 ' Initialize our index
     J1 = 0
     FOR I = 1 TO MaxColors ' process each color
     	J = INSTR(J1 + 1,MasterColors,",") ' find the next occurance of the , separator
    	 	Temp = MID(MasterColors,,J,J1 - J) ' extract the actual color between commas (starting at J and for length J1 -J)
    	 	Colors(I) = Temp ' assign the actual color to our array now.
     NEXT
END SUB


It looks more complicated than the original (and it is), but if you need to add more colors (or subtract colors) all you have to do is change the value of MaxColors and our MasterColors string, and everything continues to work properly!
The lines:

     J = INSTR(J1 + 1,x,",")
     Temp = MID(x,,J,J1 - J)
     y(I) = Temp 


are what are known as a "pattern" in computer jargon. A "pattern" is merely a programming idiom (like an English idiom...if you don't know what "idiom" means, look it up.) or a way of programming a common task. Something you'll do again and again. And what this tells me (and should you at this point) is that it belongs in its own subroutine or function...I'll leave writing this function as an exercise for you to solve. I have one that I use all the time to parse a string delimited by commas. It's a very useful routine, and you should have one in your own bag of tricks!
On to our next topic:

FOR EACH..NEXT

The FOR EACH statement is a very useful way of going through an array and doing something for each (hence the name) element in the array. It's syntax is easy:

     FOR EACH  IN 
     ....do stuff
     NEXT
      is the item at a given index into the array. Usually you give it a more descriptive name than I, or J (which is typical for a normal FOR      NEXT).  is the array you want to do things to. For example lets      say you want to have an array of 100 numbers where the value of the element      is the index value. That is, element 33 has the number 33 in it, the element      56 has 56, etc.
     DIM NumberArray(100) ' our array
     DIM I ' a number
     I = 0
     FOR EACH Number IN NumberArray ' Number automatically becomes the element at a given index.
    	 	Number = I
     	I = I + 1
     NEXT
     Yes:
     FOR I = 0 TO 100
     	NumberArray(I) = I
     NEXT

is better, I just made up the example to show you the differences. The FOR EACH doesn't require you to DIM the index., the normal FOR does. The FOR EACH is a bit more readable (understandable) than the normal FOR. Here's another example. The FOR EACH doesn't use a subscribe (index) into the array to get an element, the FOR does. Let's print out our Colors array from the code above:

     FOR EACH Color in Colors
          PRINT Color
     NEXT
      

is a lot easier to program and understand than:
     FOR I = 1 TO MaxColors
          PRINT Colors(I)
     NEXT



That's the FOR EACH loop. Once you get used to using it you'll like it. Now to our object of the day.


PICTUREBOX


A PictureBox is one of the most complex objects you'll deal with. It's complexity lies in the different properties, events, and methods it allows you to manipulate. At its core, a PictureBox allows you to draw text and graphics in a contained area on the screen.
You already know how to create one:
     ADDOBJECT "PictureBox","MyPictureBox,"10,10,200,200


I suggest first reading the manual to get a feel for the different things you can do with a PictureBox. Then try to write a program that uses them. Here's a quick run through of the things a PictureBox has:


Properties:
• BorderStyle - 0, blends with the window, 1, has a border.
• DrawWidth - a number specifying how thick lines will draw.
• FillColor - enclosed polygons (circles, rectangles, etc. can be drawn with a single command) can be filled with a color
• FillStyle - 0 solid, 1 transparent
• FontTransparent - True/False (no I don't know why this isn't 0,1)
• Picture - you can pass in the name of a graphics file (it has to be a *.bmp) and the picture will automatically draw itself into your picturebox.
• Scaleheight/Width - you can specify how things get scaled in the picturebox
• ScaleLeft/Top - left and top edges of the object
• ScaleMode - this is a MS thingy. Most of the time you want to set this to 3 (pixels) otherwise you'll wonder why things don't draw the way you expect. For more info, find some MS documentation online.


Methods:
• Cls - Erases the picturebox contents
• DrawCircle - Draws a circle, or ellipse. You can specify the radius, color, etc.
• DrawLine - This lets you specify a line or set of lines. You can also set a flag to specify you want to draw a box (rectangle or square).
• DrawPicture - lets you draw and manipulate a bitmap image file (*.bmp)
• DrawPoint - just what it says. Turn on a single pixel.
• DrawText - pretty useless since it doesn't let you specify WHERE in the box you want to draw the text. Might be useful for debugging.
• Refresh - redraw the contents of the PictureBox (if something needs to be redone because something covered the PictureBox say.)
• ScaleX, ScaleY,SetScale - lets you convert scale values
• TextHeight, TextWidth - Returns the height and width of the heighest or widest lines of text. Used with DrawText.
Events:
• KeyDown - key is pressed
• KeyUp - key is released
• KeyPress - KeyDown followed by KeyUp
• MouseDown, MouseUp - mouse clicks
• MouseMove - MouseDown and then you move the mouse (like a drag).


Yes the number of Properties, Methods, and Events is large, but taken individually, they aren't too confusing. The best way to learn about the PictureBox is to use it. So...


For next time

Using the Colors program,
- Add a PictureBox object and draw a filled box of the given color whenever the user Adds a color to the list. (Just have one colored box in the PictureBox at any given time. Draw the last added color.)
- When the user taps a key on the keyboard. Draw the letter inside the picturebox.
- When the user taps on the colored box, display a message with the name of the color being tapped.

We'll also go over the PRINT statement, the REDIM statement, and the TextBox object!

Cheers!

ARTICLE 1--The Package and Installation

Programming Using NSBasicCE

ARTICLE 1--The Package and Installation

All content (c)1999, 2002 Serg Koren.

All rights reserved.

If you know BASIC and you've already gotten and successfully installed your copy of NSBasic, congratulations! You can skip the rest of this article and check back next time. However, if you're a total newbie at things-computer, this is for you. We'll step you through getting NSBasic installed on your Casio E105 and working. First, however, we'll start with a brief description of BASIC in general (NSBasic specifically) and what you get.

BASIC

BASIC is one of the older computer languages, and exists on pretty much every computer platform available. It's called BASIC because it is--basic that is. It's usually the first language people learn when they want to learn programming. When it first came out the only other languages available on pcs (which were new then) were assembly and machine language. Machine language is just that--its the language the machine (hardware) understands. Just 0s and 1s, and you programmed by toggling physical switches. Each switch when on represented a 1 and when off a 0. So a bunch of switches on the front panel of your pc might be set to:

01101010

which meant something simple to the computer (like remember a 2 because I want to add something to it). No fooling! Programming was hard and tedious. Assembly language was a big step forward. Somebody got smart and figured out how to hook up a keyboard to the pc. But you could still only program at a very low level. Assembly language was easier to program, but it was difficult to read and understand. For instance the switches (bit pattern) was replaced with:

MOV A,2

which meant, MOVe 2 into the Accumulator. Accumulator? An accumulator holds a single number to be accumulated (added to) with another. You can only do addition when you come right down to it. To subtract you'd add a negative number...but that's another story. Multiplication and division were done via multiple adds (or adds of negative numbers).

Then someone thought, hey wouldn't it be neat if we could program in something closer to English? And BASIC was born. BASIC used simple understandable English words to denote commands to the computer. Additionally, simple math was born via the normal school symbols +,-,/,* (well keyboards don't have a multiplication symbol, so they replaced it with an asterisk.)

And everyone loved it (and pretty much still do); but as new computers and companies started up, each wanted to make their own BASIC, and they wanted it to be better (or at least different from) than other BASICs out there. So BASIC begat BASIC begat sort-ofBASIC begat well its close to BASIC. A plethora (I've always wanted to use that word in an article) of BASICs emerged. All were similar, but few would run on each other's machines. Babylon reborn!

Well it didn't quite work like that, and it's not quite that bad, but close enough. If you're at all familiar with computers you've probably heard of "Standards" or "Standard Committees". Standards are a set of rules that make something consistent. It's a big thing now. Computer stuff needs to be "standard" so that you can buy a copy of X-BASIC and it will run on Y-Hardware. You don't have to pay big bucks for Y's version of BASIC that ONLY runs on Y-Hardware. The problem is, is that BASIC has a fairly weak standards committee (a bunch of people who make up the standard), so you still see X-BASIC that ONLY runs on X-Hardware.

So what does all of this have to do with NSBasic? Well in one word, Microsoft. Microsoft is well known (and infamous) for having an ego. They are so big, they feel that their way IS (or at least should be) a standard. I won't start here, but you get the point. The problem is, is that WindowsCE uses a version of BASIC built-in that is similar (although not identical to) BASIC (VisualBasic) on the desktop. Both have similar guts, but not identical. NSBasic uses the guts to do what it has to do to get your program to run. So if you're new to WindowsCE, but familiar with VisualBasic on the desktop, you'll be somewhat surprised (I hope) to hear that NSBasic isn't VisualBasic. NSBasic/CE is a version of BASIC. There are tons of BASIC and VisualBasic books out there (just check your local Amazon.com). The problem is, is that although NSBasic/CE is similar to BASIC, you can't just pick up a BASIC book type in the code you find and hope it runs on your Casio.

Hopefully, the above will save you some hassles in terms of running out and buying a ton of VisualBasic books and wondering why the code you typed in doesn't run. The books are useful, they give you ideas and ways of doing things, but save your money. If you don't already know BASIC (any flavour), then you're better off without them. The books will only confuse you. Which brings us to the NSBasic/CE package...

The Package

NSBasic/CE comes in two pieces. You get a CD-ROM full of NSBasic, sample programs, "goodies", and other stuff. The second piece is the compact manual. If you're new to NSBasic/CE, this is your best friend. It doesn't tell you how to program, but it tells you what you can do and how you can do it. It's a reference manual, meaning that it describes each of the commands that NSBasic has. It's a good exercise (and no not boring) to just sit down and read the manual cover to cover when you first get it (one of the few manuals I suggest you do this with). It's well written and even if you don't know anything about BASIC, you'll pick up a lot just by going through it once. Don't try to memorize everything or learn it all. Just read it like a novel. That way you get a feel for the language, and what you can do. So, when you say "gee I wish I could do..." you'll remember that you saw something like that in the manual. Basically, if you don't know what's in the manual, you don't know that you can do it easily.

The manual isn't perfect. It doesn't have a few things which are part of NSBasic/CE, but it has most of it. The missing pieces you can get from the website's support page. These pieces are a bit more advanced usually, but you should check out the support page and browse through the downloads and tech notes pages. Also, you should make it a habit to visit the web message board that NSBasic has set up. This is your 2nd line of defense. Here you can see what others are doing, what problems they are having, and what solutions are offered. You can also post your own problems, questions, and suggestions. Don't be shy. Even total newbies are welcome. And, the people of NSBasic Corporation watch the board regularly and post useful stuff. The board may be a bit intimidating because there is so much stuff there (and it's not well organized) but its a wonderful resource. Ok, you've opened up your box from NSB and have stared at the CD and read the manual, and browsed the board. Time to install...

Installation

Ok, first things first. If you haven't done so already, make sure you have Windows Services (now known as ActiveSync 3.0...PLEASE upgrade your WindowsCE Services to this if you haven't done so...it's lots slicker and faster and fixes a lot of problems). You can find ActiveSync at: http://www.microsoft.com/windowsce/products/highlights/activesync.asp

Make sure you can successfully sync your Casio to your desktop. (Yes I know this is very basic, but if you can't do this you can't do anything else.)

Ok, now pop your NSBasic CD into your drive, and double-click the Readme document you find in it to launch the installer. The installer is set up to run from within the Readme document. Read (or at least browse) the readme document to see what's new, what known problems exist in NSBasicCE, etc.

Here's the confusing bit. The Readme document and the CD let you install NSBasic on a bunch of different types of hardware. HP Jornadas, Casios, Mobilons, etc. You must make sure you install the correct version of NSBasic for the hardware you have, or nothing will work and you'll wonder why. I once in a rush installed NSBasic and it didn't run until I realized I'd made the wrong choice during the installation. Be careful.

Since this article is about Casios, we'll walk through the Casio installation. The Casio E105 is a Palm-size PC. Luckily, this installation option is the first one found on the Readme document. "Palm-size PC Installation Instructions." This consists of seven steps (6 if you're not upgrading). Do these in order to avoid problems. Here's the second complicated bit--this is as complicated as it gets...which isn't very. Click on each link in turn and make sure you choose the Run this program from its current location option. Otherwise nothing will install and you'll wonder what happened. Each step will bring up your Active Sync (or WindowsCE services) installation dialog. Just follow the prompts and make sure you answer Yes to install in current directory. You may be wondering what gets installed. The first step, Basic Setup installs the NSBasic editor, help files, pretty much the guts of NSBasic/CE. Goodies Setup installs sample files. The Scripting Engine setup installs the Microsoft "guts" we mentioned earlier. The last step, System Files, installs various add on pieces that either NSBasic uses directly or you can use from your own programs.

Don't' forget to enter your serial number into the Installer application on your Casio when done.

That's it. Uh no not really. There's one step that you need to do (which isn't documented). Once you've installed NSBasic/CE on your Casio, log onto the NSBasic website and download any upgrades/updates to your version from the support page. Make sure you get the latest version if you didn't get it on the CD. Install any updates (you may not need to).

That's it. Now you're done.

I'm sure you're antsy to program, so we'll quickly run a test program to make sure everything is installed ok. This is your typical (and highly boring) "Hello world" program that always gets written when you first start learning a language...don't ask why, it's pretty stupid, but it works.

Start NSBasic from the Start menu of the Casio. You'll find it under Programs, labeled BASIC. This will bring up the NSBasic editor. For now ignore everything and just type or copy/paste in the following line into the blank area of the editor:

MSGBOX "Hello there. This is NSBasic/CE"

Double-check for typos. Then in the menubar hit the right-arrow button. This will run your program. If everything works properly you should get a new window pop up with the message "Hello there. This is NSBasic/CE". If you get the message "Microsoft VBScript compilation error - line 0, char 10 Unterminated string constant" (or something similar) you probably typed a ' instead of a " (or forgot one of the quotes). Fix the typo and try again by hitting the arrow button. If you get the message "Microsoft VBScript runtime error - line 0, char 0 Type Mismatch: " (or similar) that means you misspelled MSGBOX. Fix the typo and try again.

You should at this point have the dialog with "Hello there. This is NSBasic/CE". If you fixed the typos and you still get an error message you probably skipped an installation step somewhere. You should reinstall and try again. If after reinstalling and trying the above program you still have problems, you probably have a real problem with NSBasic or your setup and you should post a message on the webboard explaining the problem and the exact message you get.

Hopefully, and in most cases you'll get the above program to run. As I said, it's not exciting but it proves you've got a good installation of NSBasic. We won't explain what the program does right now. Just believe me, you wrote your first program. You can close the dialog using the close or Ok button. This will leave you at a blank screen. Close this screen using the close box and you should be back at the NSBasic editor with your program as you typed it. You can quit now. You don't have to save the program, if you don't want.

Well, that's it for this installment. Hopefully, you're still here. Next time, we'll go over the NSBasic editor, and describe what all the menus do, and do some more interesting programming for the beginner.

nsblogo2

ARTICLE 13-PRINT, REDIM, and the TEXTBOX

Programming Using NSBasicCE


ARTICLE 13-PRINT, REDIM, and the TEXTBOX

All content (c)1999 Serg Koren.
All rights reserved.



 

Welcome to the thirteenth installment of NSBasicCE.

This time around we discuss the PRINT and REDIM statements, and the TEXTBOX object a hodgepodge of miscellaneous commands.

If this article is a bit disjoint, please excuse me since I'm trying to figure out where I left off ;-)
 
Leftovers from Last Time
 


I asked you to modify the Colors program from last time to:
- Add a PictureBox object and draw a filled box of the given color whenever the user Adds a color to the list. (Just have one colored box in the PictureBox at any given time. Draw the last added color.)
- When the user taps a key on the keyboard. Draw the letter inside the picturebox.
- When the user taps on the colored box, display a message box showing the name of the color

' I won't reproduce the entire program (check the archives if you missed it),
'  but just give you the changes.
' Add another global array to hold actual colors instead of color names...
DIM vbColors(7) ' will be loaded with color values
DIM TheColorText ' the color to draw box
' Sub to create our PictureBox object
SUB CreateMyPictureBox
     ADDOBJECT "PictureBox","MyPictureBox",10,100,110,200
END SUB
' Sub to draw a filled box of a given color inside the picturebox
' Note that to draw a box you use the DrawLine method of the PictureBox (see manual)
SUB DrawFilledBox(WhichColor)
     MyPictureBox.Cls ' clear the old stuff out of the picture box
     MyPictureBox.DrawLine 110,110,400,400, Which, True, True       ' The last two parameters determine that a box is drawn and that it is filled
END SUB

' Subroutine to draw a character in our PictureBox
' This is how you would draw a character (or any string) in the picture box, but NOT when you tap a character on the keyboard.
SUB DrawCharacter(Which)
     MyPictureBox.Cls 'clear the old stuff in the picture box
     MyPictureBox.DrawText Which
END SUB

' Modify SETUPCOLORS to create our vbColor array
SUB SETUPCOLORS
<... leave the original code in here>
     ' Note that you have to create some colors yourself since they are not defined...see manual
     vbColors(1) = vbRed
     vbColors(2) = 256 + (128 * 256) + (64 * 65536)) ' orange RGB values
     vbColors(3) = vbYellow
     vbColors(4) = vbGreen
     vbColors(5) = vbBlue
     vbColors(6) = 128 + (0 * 256) + (128 * 65536)) ' indigo RGB values
     vbColors(7) = 128 + (0 * 256) + (255 * 65536)) ' violet RGB values
END SUB 
' Modify our Add handler to read...
SUB Add_Click
     DIM TheColor ' color value to draw the box in
     ' add the selected listbox item to the end of the listbox list
     TheColorText = MyListBox.List(MyListBox.ListIndex) ' MyListBox.List() returns the text in the list
     MyListBox.AddItem TheColorText
     TheColor = vbColors(MyList.ListIndex) ' get the color values to use in drawing the box
     DrawFilledBox(TheColor)
END SUB 
' Our handler when the user taps a key...
' NOTE: You have to tap the picturebox first to make it the active control before typing.
SUB MyPictureBox_KeyPress(Key)
     DrawCharacter(CHR(Key)) ' Key is a key value which must be converted to a character via the CHR function
END SUB 
' Our handler to display the name of the drawn color when the user taps on the PictureBox
SUB MyPictureBox_MouseDown
     MSGBOX TheColorText ' draw the saved name of the last color drawn (even if we've erased the PictureBox)
END SUB
 

PRINT


The PRINT statement is mildly useful in displaying text on the main output screen and it will write on top of everything else in your program. Unfortunately, there's no way to specify where to put the text it writes. The PRINT system is a holdover from old-style BASICs. It's syntax is straight-forward. Just follow the PRINT statement with a comma sepated list of things to display:

 PRINT 1, "test", Colors(1)


You're probably better off using other controls or using the MSGBOX.

REDIM

REDIM is a useful statement when you don't know the size of an array when the program starts. It's also useful if you need to reclaim space used by an array because you're done with it and your program is running out of memory. To use it you declare a variable that you want to use as an array, but you declare it normally (not as an array).


 DIM MyFutureArray


Now lets say you've figured out that you need an array that is 200 items in size. You use the REDIM command to resize the variable...


REDIM MyFutureArray(200)


Later if you find out your actually needed 2000 you can do a:


REDIM MyFutureArray(2000)


in your program.
To free up the memory used by the array (assuming you don't need it anymore) you can use REDIM as follows:


REDIM MyFutureArray(0)


You can also do things like:


REDIM MyFutureArray(100,100)


You probably won't use REDIM often, but it's useful in your NSBasic bag of tricks.


TEXTBOX


The TEXTBOX object is used to display an editable text field on a form. Up until now we've been using INPUTBOX to get user input, but the TEXTBOX is much more natural. Creating a TEXTBOX object is identical to other objects, so we won't go over that. The TEXTBOX object has a few new properties that deal with what text is selected.
selLength is a property that returns the length in characters of the selected text.


selStart returns the position of the first selected character.
selText returns the actual selected text.


The only other new property you have to worry about is MutliLine which is a Boolean (TRUE or FALSE). If it's set to TRUE, the TEXTBOX will allow the user to enter carriage returns and multiple lines of text. Otherwise, the TEXTBOX will only allow a single line of text.


That's it for this time around. Next time we'll go over TIME, Time, TIMEVALUE and TIMESERIAL In other words, we'll deal with statements, functions, and objects dealing with time.


For next time


Something simple! Write a program with a TEXTBOX and CommandButton. When tapped the button should display the selected text, and its length.

Cheers!

ARTICLE 10-DECISION, THE LABEL AND LISTBOX

Programming Using NSBasicCE

ARTICLE 10-DECISION, THE LABEL AND LISTBOX

All content (c)1999 Serg Koren.
All rights reserved.


Welcome to the 10th installment of NSBasicCE. This time around we talk about getting your programs to make decisions, and we talk about two widgets: the label, and the listbox.

Leftovers from Last Time 

Last time around we talked about arrays and how they simplify coding. I also asked you to write a simple program that uses arrays.

The program should have:

  1. 3 CommandButtons labeled "A","B", and "C"
  2. A CommandButton labeled "Do it!"

The program should:

  1. Tally the numbers of times each of the three CommandButtons has been tapped. (Hint: This is what the array is for).
  2. Prompt the user for his name when he taps the "Do it!" button, and then display a message in the format: " Hi <name here>, you've tapped button A x times, B y times, and button C z times."

Here's my code. 

       '-------------------code starts here
       ' Assignment number 9
       '
       OPTION EXPLICIT
       DIM TapCount(3) ' we won't use element 0 for anything. Used to store the count of taps for a given button.
       DIM AButton, BButton, CButton ' used to index into TapCount array
       
       '--------------------create our objects
       ' Create our Command buttons
       SUB CreateMyCommandButtonA
      	  ADDOBJECT "CommandButton","A",10,10,100,30
      	  A.Caption = "A"
       END SUB
       
       SUB CreateMyCommandButtonB
      	  ADDOBJECT "CommandButton","B",10,50,100,30
      	  B.Caption = "B"
       END SUB
        
       SUB CreateMyCommandButtonC
      	  ADDOBJECT "CommandButton","C",10,90,100,30
      	  C.Caption = "C"
       END SUB
       
       ' Create our DoIt button
       SUB CreateMyCommandButtonDoIt
          ADDOBJECT "CommandButton","DoIt",10,130,100,30
       	  DoIt.Caption = "Do It!"
       END SUB
       
       '----------------- our event handlers
       SUB A_click
      	  TapCount(AButton) = TapCount(AButton) + 1
       END SUB
       
       SUB B_Click
      	  TapCount(BButton) = TapCount(BButton) + 1
       END SUB
       
       SUB C_Click
      	  TapCount(CButton) = TapCount(CButton) + 1
       END SUB
       
       SUB DoIt_Click
      	  DIM MyName ' this is local because it's not used anywhere else!
      	  MyName = INPUTBOX("Please enter your name",vbOKOnly,"PROMPT") ' ask user for name
      	 ' now display the message: "Hi , you've tapped button A x times, B y times, and button C z times."
      	 MSGBOX "Hi " & MyName & ", you've tapped button A" & TapCount(AButton) & " times, B " & TapCount(BButton) & ",times and button C" & TapCount(CButton) & " time."
       END SUB
       
       '----------------------------------Setup routines
       SUB SetupUI
      	  CreateMyCommandButtonA
      	  CreateMyCommandButtonB
      	  CreateMyCommandButtonC
      	  CreateMyCommandButtonDoIt
       END SUB
       
       ' Initialize global variables
       SUB Iniaialization
      	  AButton = 1 ' point to first element of TapCount array for button A
      	  BButton = 2 ' point to second element of TapCount array for button B
      	  CButton = 3 ' point to third element of TapCount array for button C
      	  TapCount(AButton) = 0 ' set count to 0 for first element
       	  TapCount(BButton) = 0 ' ...and so on
      	  TapCount(CButton) = 0
       END SUB
       
       ' Our main routine
       SUB Main
       	  Initialization
      	  SetupUI
       END SUB
       
       Main ' our IMMEDIATE command to start everything
       '--------------------code ends here 
       

Not too bad! Now look at our Initialization routine in the above code. Seems like there should be an easier way of doing this....and there is! We'll talk about how later in this article, but first, we'll get your programs to make some decisions on their own!


IF THEN...ELSEIF....END IF (DECISIONS)

So far we've just dealt with programs that execute line by line by line by line...top to bottom. Now we'll talk a bit about altering the execution flow. That is, how to get your program to skip some code and execute other code. To do this, your program has to decide somehow that it should execute some portions of code while avoiding others. NSBasic has one statement that allows this: The IF/END IF statemennt. If you look in the manual under IF...THEN...ELSE you can see the hoary details. I'll break it down to simplify it and work up. In it's simplest form, the IF/END IF statement looks like:

      IF  THEN
         ....execute this code here, if  is TRUE
      END IF 


This variation, just lets your program decide <something> and if the result is TRUE your program will execute everything between the IF...THEN and END IF statements. What happens if <something> is FALSE? NSBasic ignores everything betweent he IF...THEN and END IF statements and starts executing at the line after the END IF. Let's take at a more concret example.

 

   DIM TonsOfConcrete
   TonsOfConcrete = 3
   IF TonsOfConcrete < 5 THEN
      MSGBOX "You don't have enough concrete!"
   END IF 
  TonsOfConcrete = TonsOfConcrete + 3 ' buy more concrete   IF TonsOfConcrete < 5 THEN       MSGBOX "You still don't have enough concrete"   END IF


 
In this example, the first IF statement returns TRUE (TonsOfConcrete IS less than 5), so you see the first MSGBOX. Once you add 3 to TonsOfConcrete the second IF statement returns FALSE (TonOfConcrete is now 6 which is not less than 5 (FALSE)), so you don't see the second MSGBOX. One thing to note here is that <something> returns a value. So you can use a FUNCTION there...
 

    IF INPUTBOX("Enter a number 1..10") < 5 THEN         MSGBOX "Less than 5!"     END IF


That's fairly easy to understand if you're following everything we've done so far! Ok now what happens if you want to display one message if the number entered is less than 5 and another if its greater than or equal to 5? Well you could do:

      Num = INPUTBOX("Enter a number 1..10") 
      IF Num < 5 THEN           MSGBOX "Less than 5!"       END IF
      IF Num >= 5 THEN
          MSGBOX "Greater than equal 5!"
      END IF 
 
This is fine unless someone goes in and adds the line "Num = 3" between the first END IF and the next IF! NSBasic has a form that lets you execute one set of code under one condition and another if the condition is false...
 
	IF  THEN
	   < do this>
 	ELSE
	   < do this if  is false
 	END IF 
 
Let's get concrete again..
 
 	IF TonsOfConcrete >= 5 THEN
	   MSGBOX "Lots of concrete!"
 	ELSE
     	   MSGBOX "Warning, you have less than 5 tons of concrete!"
 	END IF 
 
And what if we want a special message for 2 tons? Well we use the form:
 
 	IF  THEN
	   < do stuff here>
	ELSEIF  THEN
	   < do other stuff here>
  	ELSE
           < do something different if none of the above is true>
  	END IF
	IF TonsOfConcrete = 2 THEN
      	   MSGBOX "2!"
        ELSEIF TonsOfConcrete < 5 THEN
       	   MSGBOX "Buy more!"
        ELSE
       	   MSGBOX "Enough!"
        END IF 

 
And you can have as many ELSEIF...THEN statements in your IF statement as you need! One thing you should be careful of is that the order of the tests is important. The first one that evaulates to true gets done! The others are ignored. For example compare what happens with the prior IF and this one...


	IF TonsOfConcrete < 5 THEN
       	   MSGBOX "Buy more!"
        ELSEIF TonsOfConcrete = 2 THEN
           MSGBOX "2!"
        ELSE
           MSGBOX "Enough!"
        END IF 

 
If you can understand what happens and why, you have IF/END IF statements down! Think about it.
Time to look at our UI widgets for this week..we handle two!

LABEL

The label widget places a line of text on your program's main window. You already know how to create a label, and what most of the Properties, Events and Methods do. You should still check out Label in the manual. There really isn't much new with this widget apart from the Alignment property. The alignment property lets you specify whether the text in the label lines up on the left, the right or in the center of the label. You use a number to determine alignment: 0 = left, 1 = right, 2 = center. For example:
 

      ADDOBJECT "Label","MyLabel",10,10,100,30
      MyLabel.Caption = "Hi!"
      MyLabel.Alignment = 2 ' center 


Again, if your label isn't wide enough, the Alignment property won't have any visible effect.
 
And now onto something slightly similar...


LISTBOX


The Listbox is very similar to the ComboBox. Both present you with a list and let the user choose one of the items in the list. When would you use a ListBox, and when a ComboBox? Typically, I choose a ComboBox when the user needs to type a new item into the list (add an item to the list). I use a ListBox whenever the list items are fixed and the list items have to be visible (A ComboBox's list items are only visible when the user taps on the ComboBox to drop the list down.) Other than that the two serve identical purposes. Because of that the ListBox has similar Properties, Methods, and Events. The exceptions being, that there is no DropDown event in a ListBox. A ListBox also has a Property called ScrollBars. This is because a ListBox can have more items than will fit in the displayed size of the box. The manual implies you can have horizontal, vertical or both types of scrollbars. Actually, only vertical (2), is supported. Just like a ComboBox, you can add, remove items in the list, as well as clearing the entire ListBox. Play with the ListBox's scrollbar propery! But be aware, that you have to set the ScrollBars property immediately after you create the listbox.
 

      ADDOBECT "ListBox","MyListBox",10,10,100,100
      MyListBox.ScrollBars = 2 ' vertical
      MyListBox.AddItem "AAAAAAAAAAAAAAAA"
      MyListBox.AddItem "AAAAAAAAAAAAAAAA"
      MyListBox.AddItem "AAAAAAAAAAAAAAAA"
      MyListBox.AddItem "AAAAAAAAAAAAAAAA"
      MyListBox.AddItem "AAAAAAAAAAAAAAAA"
      MyListBox.AddItem "AAAAAAAAAAAAAAAA"
      MyListBox.AddItem "AAAAAAAAAAAAAAAA"
      MyListBox.AddItem "AAAAAAAAAAAAAAAA"
      MyListBox.AddItem "AAAAAAAAAAAAAAAA" 
 
Nothing too complicated there, apart from having to set the Scrollbars property right after the ADDOBJECT statement. (This is indicated by a + sign in the manual on the page dealing with Properties).


For Next Time

The assignment for this time will test everything we've gone over so far. Write a program,
 
That has:


  1. A Listbox
  2. A Label next to the listbox labelling it "Colors"
  3. An array of colors: "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"
  4. A CommandButton labelled "Remove"
  5. A CommandButton labelled "Add"
  6. A CommandButton labelled "Find Missing"
  7. A CommandButton labelled "Find Duplicates"

The program should:

  1. Load the colors into the listbox
  2. When the user clicks on the "Remove" button , the selected color in the listbox is removed from the list.
  3. When the user clicks on the "Add" button, the selected color is added to the end (bottom) of the listbox.
  4. When the user clicks on the "Find Missing" button, the program should list all the missing colors in the listbox from the master set.
  5. When the user clicks on the "Find Duplicates" button, the program should list all the colors in the listbox that occur more than once.

 
Next time we'll go over getting your program to do things more than once (loops) as well as the OptionButton and PictureBox objects!
If you get stuck or have a question about anything we've gone over, feel free to e-mail me at Serg@VisualNewt.com
 
Cheers!
 






ARTICLE 4--CommandButtons

Programming Using NSBasicCE

ARTICLE 4--CommandButtons

All content (c)1999, 2002 Serg Koren.

All rights reserved.

Welcome to the forth installment of NSBasic.

This time we go over the most common user-interface object you will use: CommandButtons.

Leftovers from Last Time

Last time I we talked about Objects, Properties, and Methods, and I gave you a simple program that had a ListBox object that hid when you double-clicked it:

'---start code here--- ' 
' A simple program that creates a ListBox and lets us show and hide it by clicking on it 
' 
' A subroutine to create a ListBox on the screen 
SUB MakeAListBox 	
    ADDOBJECT "ListBox","MyListBox",50,50,100,100 ' create an empty ListBox 
END SUB         

' A SUB to handle a DblClick Event (a Click event handler) for the ListBox called "listbox" 
SUB MyListBox_DblClick 	
    MyListBox.Hide ' Hide listbox 
END SUB         

' Our main routine where the main things happen...good to always have one 
SUB Main 	MakeAListBox 
' create a ListBox 
END SUB         

Main ' our one and only Immediate command for this program to run the Main SUB '
---end code here---

I then asked you to write a short program (like above), but include a CommandButton Object. The program should have:

1) A ListBox

2) A CommandButton

The program should:

1) Hide the ListBox when you double-click it.

2) Unhide (use the Show method) the ListBox when you tap (Click) the CommandButton.

And I promised to show you one version of the code (and a simpler version).

Here's the version you probably came up with (or a something very similar):

'---start code here--- 
' 
' A simple program that creates a ListBox and lets us show and hide it by clicking on it 
' 
' A subroutine to create a ListBox on the screen 
SUB MakeAListBox 		
   ADDOBJECT "ListBox","MyListBox",50,50,100,100 ' create an empty ListBox 
END SUB   

' A subroutine to create a CommandButton on the screen 
SUB MakeACommandButton 		
   ADDOBJECT "CommandButton","MyCommandButton",50,75,100,50   ' create a CommandButton named MyCommandButton 
END SUB  

' A SUB to handle a DblClick Event (a DblClick event handler) for the ListBox called "MyListBox" 
SUB MyListBox_DblClick 		
   MyListBox.Hide ' Hide MyListBox 
END SUB  

' A SUB to handle a Click Event (a Click event handler) for the CommandButton called "MyCommandButton" 
SUB MyComandButton_Click 		
   MyListBox.Show  ' Show the ListBox "MyListBox" when the user clicks "MyCommandButton" 
END SUB  

' Our main routine where the main things happen...good to always have one 
SUB Main 		
   MakeAListBox         ' create a ListBox   
   MakeACommandButton   ' create a CommandButton 
END SUB  Main ' our one and only Immediate command for this program to run the Main SUB 
'---end code here---

The new code consists of the MakeACommandButton and MyCommandButton_Click subroutines, plus the MakeACommandButton line in the Main subroutine.

The points to remember from last article are:

  1. Call Methods using the name of the object, a period, and the name of the Method: MyListBox.Show
  2. Write event handlers using the name of the object, an underscore, and the name of the Method (event to be handled): MyListBox_DblClick

Now this looks like a lot of code (believe me it isn't) and complicated (again it isn't). If you followed the last article this should all make sense, if not reread the last article or email me with questions (Serg@VisualNewt.com).

The one question you may be asking, is why do we use a DblClick (double-click) for the list box, instead of a Click as in the CommandButton? Apart from letting you use more than one type of Method and event handler, the ListBox only responds to single clicks (Click) if there is something in the listbox to click on. Otherwise it only responds to DblClick events. (We'll talk more about Events in the next article).

Now for the simplification (believe me it is). Look at the Main subroutine. It calls two subroutines which "make" or "setup" things. Specifically, the methods set up parts of the user interface. What we can do is factor (like in math...remove the common bits) that code out into a separate subroutine, and replace it with a single call to a subroutine in Main. Like this:

SUB Main 		
   SetupUI  ' call a routine to setup our User Interface 
END SUB

So we replaced two lines of code (which did similar things...namely setting up parts of the User Interface) with a single line of code. That's simplified it. But what is this thing called "SetupUI"? It's a call to a new method we write using the lines we took out! Like this:

'   A subroutine to set up all the bits of our user interface (controls). 
SUB SetupUI 	
   MakeAListBox  ' create a ListBox 	
   MakeACommandButton ' create a CommandButton	 
END SUB 
 So our new (simplified) program now looks like: 
 
'---start code here--- 
' 
' A simple program that creates a ListBox and lets us show and hide it by clicking on it 
' 
' A subroutine to create a ListBox on the screen 
SUB MakeAListBox
   ADDOBJECT "ListBox","MyListBox",50,50,100,100 ' create an empty ListBox 	 
END SUB 

' A subroutine to create a CommandButton on the screen          
SUB MakeACommandButton 	
    ADDOBJECT "CommandButton","MyCommandButton",50,75,100,50 ' create a CommandButton named MyCommandButton  
END SUB   

' A SUB to handle a DblClick Event (a DblClick event handler) for the ListBox called "MyListBox" 
SUB MyListBox_DblClick 	
   MyListBox.Hide ' Hide MyListBox 		
END SUB  

' A SUB to handle a Click Event (a Click event handler) for the CommandButton called "MyCommandButton" 
SUB MyComandButton_Click 	
   MyListBox.Show  ' Show the ListBox "MyListBox" when the user clicks "MyCommandButton" 	
END SUB   

'   A subroutine to set up all the bits of our user interface (controls). 
SUB SetupU
       MakeAListBox  		' create a ListBox
       MakeACommandButton ' create a CommandButton 
    END SUB   

    ' Our main routine where the main things happen...good to always have one 
    SUB Main 	
       SetupUI   ' set up our controls 		
END SUB  Main ' our one and only Immediate command for this program to run the Main SUB 
'---end code here---

You may be shaking your head at this point, totally confused. How is this simpler? Right now, it looks like we've added more code and made things more complex. True we've added more code. It's false that it's more complex. The code is easier to follow, easier to understand, we know now that those two lines that we "factored out" set up our user interface, because our Main now tells us that it does. (SetupUI tells you exactly what those lines do, whereas the individual lines may be doing something else such as modifying the user interface, instead of just setting it up). Also, this is a very simple program, as you write more complex programs, you'll be putting all sorts of stuff into your Main subroutine, which would confuse any other reader (and you) about what exactly those line do.

Factoring is a common computer programming concept. It tries to replace code with a common function, with a single subroutine (or function) call, to make the code more understandable. The other reason for factoring is that it makes the factored lines (those two lines in our example) reusable. If you ever needed to set up your user interface more than once in the program you'd only have to write:

...
SetupUI
...
SetupUI
....

instead of:

...
MakeAListBox  ' create a ListBox
MakeACommandButton ' create a CommandButton
...
MakeAListBox  ' create a ListBox
MakeACommandButton ' create a CommandButton
....

Which you have to admit is a lot less typing. Factoring is a "good thing", to steal a phrase. Byte-sized chunks are easier to digest than pages of commands.

Ok...our little program doesn't do much and it really looks kind of pitiful. Our list is empty and our button looks kind of drab and not really like a button. We're going to change our program (it'll still be pitiful, but it won't look as drab.) keeping all we've gone over in mind.

CommandButtons

The CommandButton we've used is one of the two user interface controls (commonly known as widgets) you'll use most frequently. We'll start our in-depth tour of widgets with the CommandBox, and go right into the other most frequentlyused widget, the MSGBOX.

Referring to the NSBasic manual (and proven by our little program earlier), you create a CommandButton the same way you created the ListBox. The only difference in the command was that "CommandButton" followed the key word ADDOBJECT instead of "ListBox". So, from this we can see that NSBasic has a nice consistent way of creating objects. They all follow the same pattern:

ADDOBJECT "the type of object","the name you give your object", xpos, ypos, width,height

Some objects require all these pieces (such as CommandButton) while others only require some of them, but basically if you know how to create one object you know them all. The differences lie in the Events, Methods, and Properties of each object.

A CommandButton, is a simple button, that the user clicks on to get something to happen. It has some text (a label) that describes what the button does. You can change its colors and the style of the text in the label. It's a fairly simple, but very flexible object.

One thing you should be aware of is that if you look at the CommandButton page of the manual, the Properties, Methods, and Events section of the page refer you to other pages. These pages describe each of the corresponding items, and the values that you can set them to. For instance, the BackColor of a CommandButton (the color of the background--that is, the button face color) can be set to a Color...which in turn is explained on yet another page. After a while you'll remember what goes with what thing. But at first, you'll have to do a fair amount of cross-referencing. Just look up the pages Properties, Events, or Methods as needed.

Ok, back to CommandButtons. Let's give our CommandButton in our example program a title. How do we do this? Well, a CommandButton has a Property (remember this is a characteristic of the object) called Caption. And let's make the button say "Hello" on its face. Again, we refer to properties using the dot "." notation. So we would write:

MyCommandButton.Caption = "Hello"

(Remember to put words that are visible to the user, like the caption in quotes--"Hello" instead of Hello.)

Where do we put this line? Well, it's part of creating our button so put it in the bit of code that creates our button, namely "MakeACommandButton"

' A subroutine to create a CommandButton on the screen 
SUB MakeACommandButton 	
   ADDOBJECT "CommandButton","MyCommandButton",50,75,100,50   ' create a CommandButton named MyCommandButton 	MyCommandButton.Caption = "Hello" 
END SUB

Make this change to your program and rerun it. Your button now has as caption! It looks much more like a real button now. We can make the text in the caption standout, by using the FontBold property. (A Font in computer-talk is the shape of the family of letters or text being used to write with. That is, the shape when you ignore things like underlines, italics, and bold, etc.) When you cross-reference FontBold you find it's set to True/False (something known as a Boolean in computerspeak). So if we set it to True, then the text in the caption should be highlighted. Add the line to MakeACommandButton again. I'll wait for you to do it....back? Good. This is what the line looks like:

MyCommandButton.FontBold = True

When you rerun the program you see the caption is darker and stands out now. Take some time now, and play with all the other Properties of a CommandButton. Try different values for them to see their effect on your single button. A lot of these Properties are common to other objects, so if you experiment with them on the CommandButton, you'll know what they do and how to use them in other Objects.

For the time being ignore Properties labelled as (read-only) in the manual. We don't have enough programming yet under our belts to deal with read-only properties.

Onward!

A CommandButton only handles two Events (Methods you can call): Click and GotFocus. We've seen and worked with Click already; this is the Event that triggers your Click event handler method. GotFocus is a bit harder to explain. In simplest terms, GotFocus means the object has been selected (not clicked) but selected. Typically, you move the focus (selection) around by using the Tab button on the keyboard. It moves the selection (highlighting) around from object to object as you hit Tab. You can then hit the Enter key (or the Casio's Action Wheel) to generate a "click" event on that button or control that has "GotFocus". What the GotFocus event handler lets you do, is let you execute some commands whenever the object (CommandButton in this case) gets highlighted. For instance, maybe you have a message come up like a tool-tip (help bubble) whenever someone selects or highlights your button. You could do that in your GotFocus event handler (since NSBasic doesn't support tooltips).

CommandButton Methods include two that we've played with already: Hide and Show. In addition there is something called "SetFocus" you can call this method (MyCommandButton.SetFocus) to highlight the button (and consequently generate a GotFocus event, which would cause your MyCommandButton_GotFocus method to run.) Phew! Now we see some of the power of Objects! Some methods can create secondary events: Doing a SetFocus causes a GotFocus event to be created which causes your GotFocus event handler (method/subroutine) to run. Take a deep breath and reread what we've done so far. It's a lot to digest, and once you understand (or at least feel comfortable with) all this, you're on the road to being a programmer!

The last metthod a CommandButton deals with is Move. This lets you Move the button from your program--that is, alter where it sits depending on something else. Lets move our button to the right 5 units each time the user taps (Clicks) on it. Cross-referencing Move we see it takes similar values to the actual creation command...so in essence we're reacreating our button somewhere else on the screen. This should be simple then, and it is, but we haven't gone over a crucial part of programming yet, namely something known as "parameters" or "parameter passing". We'll leave this for another time.

That's all there really is to CommandButtons (and lots of other Objects) in NSBasic.

To get you used to using CommandButtons, I want you to write a program for next time.

The program should have:

  1. Four command buttons.
  2. Each button should have a different label: Bold, Italic, Underline, and Normal

The program should:

  1. Start with all captions in the default style (not Bold, Underlined, or Italic)
  2. When you hit the button that says "Bold" the label style should go bold (stand out)
  3. When you hit the button that says "Italic" the label style should switch to italics
  4. When you hit the button that says "Underline" the label style should underline
  5. When you hit the button that says "Nomal" all label styles should go normal (the default) and undo everything else.
  6. No button should affect any other button except for the "Normal" button which affects all the others.
  7. Use factoring.

It's not that hard really. Take is slow and if you get stuck reread the sections of the article that explain what you're stuck on. Check for typos, and use double-quotes! We'll go over the answer next time, and we'll finally explain what a SUBroutine really is, and get our first explanation and use of FUNCTIONs. We'll also go over our next Object, the MSGBOX.

If you get stuck or have a question about anything we've gone over, feel free to email me at Serg@VisualNewt.com

Cheers!

nsblogo2

ARTICLE 8--DISSECTING STRINGS AND THE DATE OBJECT

Programming Using NSBasicCE

ARTICLE 8--DISSECTING STRINGS AND THE DATE OBJECT

All content (c)1999, 2002 Serg Koren.

All rights eserved.

Welcome to the eight installment of NSBasicCE.

In this article follow up on the last article and talk about how to break long strings into shorter strings, and we look at a new object in NSBasic, the Date Object.

Leftovers from Last Time

Last time we talked about concatenating strings and the ComboBox. I asked you to write a program that has:
  1. Five checkboxes.Each labeled with a number “1”, “2”, “3”,”4”, “5
  2. A ComboBox
  3. A CommandButton labeled “+”
  4. A CommandButton labeled “-“
  5. A CommandButton labeled “Total”
  6. A CommandButton labeled “Clear”
The program should:
  1. Each time the user checks a number checkbox put the number the user tapped at the end of the ComboBox list.
  2. If the user taps the + or –command button, put a “+” or a “-“ at the end of the ComboBox list.
  3. If the user taps the “Total” command button, display the result of the items in the ComboBox using the message:   “There are x items in the ComboBox.”
  4. If the user selects an item from the ComboBox, display the message: “The user chose: x.”(Note the period after the ‘x’.)
  5. If the user taps on the “Clear” command button, remove all entries from the ComboBox, and deselect (uncheck) all the checkboxes.
This seems complex, but you should take it a piece at a time and build it up. A good strategy would be to take steps 1-5 in the "has" section and get them working one at a time. Then work on the "should" section. Any such "break it up" strategy would work. Here's my version of the program for your reference:
'----------code starts here
'
' Article 7 assignment
'
'----------Routines to create the UI
' set up our 5 checkboxes
SUB CreateCheckbox1
ADDOBJECT "CheckBox","Ch1",10,10,30,20
Ch1.Caption = "1"
END SUB
SUB CreateCheckbox1
ADDOBJECT "CheckBox","Ch2",10,30,30,20
Ch2.Caption = "2"
END SUB
SUB CreateCheckbox2
ADDOBJECT "CheckBox","Ch3",10,50,30,20
Ch3.Caption = "3"
END SUB
SUB CreateCheckbox3
ADDOBJECT "CheckBox","Ch4",10,70,30,20
Ch4.Caption = "4"
END SUB
SUB CreateCheckbox4
ADDOBJECT "CheckBox","Ch5",10,90,30,20
Ch5.Caption = "5"
END SUB

'----------setup our combo box
SUB CreateComboBox
ADDOBJECT "ComboBox","Cmb",10,110,60,80
END SUB

'----------set up our command buttons
SUB CreatePlusButton 
ADDOBJECT "CommandButton","Plus",10,140,20,20
Plus.Caption = "+"
END SUB
SUB CreateMinusButton 
ADDOBJECT "CommandButton","Minus",10,170,20,20
Minus.Caption = "-"
END SUB
SUB CreateClearButton 
ADDOBJECT "CommandButton","Clear",10,200,50,20
Clear.Caption = "Clear"
END SUB
SUB CreateTotalButton 
ADDOBJECT "CommandButton","Total",10,230,50,20
Total.Caption = "Total"
END SUB
 
'----------event handler for checkboxes...
' just put the number (which is the caption) into combobox
SUB Ch1_Click
Cmb.AddItem Ch1.Caption ' just move the caption of this checkbox into the last slot in the Combobox
END SUB 
SUB Ch2_Click
Cmb.AddItem Ch2.Caption
END SUB 
SUB Ch3_Click
Cmb.AddItem Ch3.Caption
END SUB 
SUB Ch4_Click
Cmb.AddItem Ch4.Caption
END SUB 
SUB Ch5_Click
Cmb.AddItem Ch5.Caption
END SUB 

'----------event handlers for buttons
SUB Plus_Click
Cmb,AddItem Plus.Caption ' just move the caption of this button into the last slot of the Combobox
END SUB
SUB Minus_Click
Cmb,AddItem Minus.Caption 
END SUB
SUB Clear_Click
Cmb.Clear ' just clear all the items in the ComboBox out
END SUB
SUB Total_Click
MSGBOX "There are " & Cmb.ListCount & " items in the Combobox." ' see explanation below
END SUB
SUB Cmb_Change ' our ComboBox event handler...see explanation below
MSGBOX "You chose " & cmb.ListIndex & "."        ' note the period at the end
END SUB

'----------main routines
' set up our user interface widgets
SUB SetupUI
CreateCheckbox1
CreateCheckbox2
CreateCheckbox3
CreateCheckbox4
CreateCheckbox5
CreateComboBox
CreatePlustButton
CreateMinusButton
CreateClearButton
CreateTotalButton
END SUB
 
' our main routine that runs everything
SUB Main
SetupUI ' create the user interface
END SUB
Main ' our only IMMEDIATE command
'----------code ends here
 
That's it. It looks like a lot, but it's not bad! We'll show you how to make it simpler and shorter next time. This is also known as "brute force" code. You force everything to happen one by one. There are more efficient ways of doing the above! Now then, everything should make sense apart from maybe the event handlers. Most of the event handlers just copy the caption of the widget clicked into the ComboBox:

cmb.AddItem <widget name>.caption

This is a shortcut for something you probably did (if you're just starting out):

 
DIM X
X = <widget name>.caption
cmb.AddItem X

would do the same thing. But my version takes less typing and once you get used to it, is easier to understand. This is a programmatic "idiom" (also known as a "pattern".) The Total button event handler just displays a MSGBOX:

MSGBOX "There are " & Cmb.ListCount & " items in the Combobox."

Again, you may have done it by DIMensioning individual strings and then concatenating them (as described in the last article) and finally passing the concatenated string to MSGBOX. That's fine too! The tricky bit is the "Cmb.ListCount" which returns he number of items currently in the ComboBox. This is a number that gets coerced into a string which is then concatenated into the rest of it. Nothing too hard.

The ComboBox event handler uses the same technique to display the item number of the item in the list that the user chose: cmb.ListIndex

Note that this doesn't show the value of the item chosen, just the ordinal location in the list of the item chosen. We'll talk about how to get the actual number chosen next time!

If you don't realize it, the above sample can be used as a basis for a simple calculator. We'll come back to this example from time to time as we learn more!

Onward to dissecting strings!

Dissecting Strings

We described how to set up strings via a DIM statement and how to assign them to variable and how to concatenate strings using & into longer strings last time. This time we talk about how to chop a string into pieces!

Let's say you have a string that someone typed in. A first name, a space, and a last name, and you want to make your program friendlier and just use the person's first name when you display a message:

Serg<space>Koren

and you want to do a MSGBOX FirstName

You could have them enter just their first name in a field, and have a separate field for the last name. But sometimes this is too much work for the user. So lets say we get the full string somehow.

DIM FirstLast
FirstLast = "Serg Koren" 
We have a string! We know how to add stuff to it such as

Prompt = FirstLast & " how are you?"

But how do you just get the first name? Or just the last name? Or maybe the space in the middle? It's not very hard, since NSBasic provides a rich set of Functions that let you do just that. Let's start simply and assume you know the length of the substring you want to extract, and that the substring starts at the very left of our parent string. Just use the LEFT function. LEFT takes two parameters, the string you want to chop up, and the number of characters from the left you want to take. What you get is a substring with those restrictions. So if we know the first name is 4 characters long:

DIM First, FirstLast,FirstLength
FirstLength = 4
FirstLast = "Serg Koren"
First = LEFT(FirstLast,FirstLength)
MSGBOX First & ", how are you?"

Again, remember that a function returns a result and uses parentheses around its parameters. That's not hard is it? Now what about the last name? How do we get the rightmost part of a string if we know the length of the substring? Just use the RIGHT function the same way! Assuming the above snippet of code exists:

DIM Last,LastLength
LastLength = 5
Last = RIGHT(FirstLast,LastLength)
MSGBOX "The last name is: " & Last

You could even put it back together!

DIM NewFirstLast
NewFirstLast = First & " " & Last
MSGBOX NewFirstLast

Important note: RIGHT, LEFT, and the other string manipulation functions we will discuss don't destroy the original string! They just make copies of parts of them!

MSGBOX FirstLast

would still show "Serg Koren", it hasn't been destroyed by LEFT and RIGHT! Now the last function MID which returns a substring from the MIDdle. MID again takes the string to chop up, but its next parameter is the starting character (a number) and then an optional length parameter to extract. For example, if we wanted to extract the space from the name we could do:

DIM Space, StartPos, Length
StartPos = 5 ' start at the 5th character of FirstLast (the space)
Length = 1 ' extract only 1 character (just the space)
Space = MID(FirstLast,StartPos,Length) ' get the space
MSGBOX Space ' display the space

Not very exciting, but it works. How do we know? Well we can figure out how many characters "Space" has. We can get the lenght of a string (the number of characters in it) by using the LENgth function:

DIM SpaceLeng
SpaceLen = LEN(Space)
MSGBOX "Space has " & SpaceLen & "      characters in it."
MSGBOX "FirstLast has " & LEN(FirstLast)      & " characters in it."

Try the above samples of code on your PocketPC, changing the lengths or the starting position. I mentioned the third parameter in MID is optional. What happens if you leave it out in the above code? You should also read the manual pages on LEFT, RIGHT, MID, and LEN. You'll be using these a lot! Ignore LEFTB, RIGHTB, LENB, MIDB for the time being. We'll go over these in a future article.

The last string function I want to talk about is REPLACE. REPLACE replaces parts of a string with another string. It's like an editor's FIND/REPLACE function. For example, if we want to change all of the "e"s in my name to "x"s we could use REPLACE. If you check the manual, you see it has a bunch of parameters, but you'll only have to worry about the first three most of the time.

REPLACE(target,find,source)

'Target' is our main string we want to modify (FirstLast in my example), 'find' is the string we want to replace (e in my example) and 'source' is the character we want to replace find with (x).

FirstLast = REPLACE(FirstLast,"e","x")
MSGBOX FirstLast
You can also do things like
FirstLast = REPLACE(FirstLast,"er","eeeeeeeer")

There is no rule that says what you replace and what you replace it with has to be one character, or the lengths have to match, but you should know what you're doing.

That's it for strings; or at least the things you'll deal with most.

Date Object

Date Objects are a new feature introduced in the latest NSBasic release. It displays a calendar widget and lets the user select a date from the calendar. Normally, it displays a date in a field. When the user taps on the date, it displays the calendar. It's useful for getting a date from the user without him having to type a date in or having to pull up another type of calendar. Creating it is easy (you should have this down in your sleep).

ADDOBJECT "Date","MyDateObject",10,10,100,20

You should note that the width and height only apply to the date field itself. The calendar isn't resizable. The new properties are: formatLong, Max, and Min formatLong has a bug in it, so ignore it until it's fixed.

Max and Min allow you to specify a range to limit your calendar to a date range. This is useful if say you want to limit the calendar selection to the current fiscal quarter, or this:

MyDateObject.Min = "07/01/1999"
MyDateObject.Max = "12/01/1999"

There are no new Methods to discuss for the Date Object, and the only new Event we can handle is something called "dropDown" which gets triggered (calls our "MyDateObject_dropDown" handler) when the user taps the the field to display the calendar.

For Next Time

This is a simple exercize to give you a break from the last one. Write an app that has:

  1. a date object
  2. a command button

It should:

  1. save the date the user taps on in a variable called TheDate
  2. Display the message: "This is the i-th day of the j-th month." whenever the user taps the command button.

Note that i and j above are numbers you can get from TheDate.

Next time I'll tackle a powerful and simplifying concept known as arrays as well as the INPUTBOX object! See you then...

If you get stuck or have a question about anything we've gone over, feel free to e-mail me at Serg@VisualNewt.com
Cheers!
nsblogo2

ARTICLE 11-DEJA-VU AGAIN

Programming Using NSBasicCE

ARTICLE 11-DEJA-VU AGAIN

All content (c)1999 Serg Koren.
All rights reserved.



 
Welcome to the eleventh installment of NSBasicCE.
This time around we talk about getting your programs to repeat commands, and we talk about our widget, the option button.
 
Leftovers from Last Time
 
Last time around we talked about getting your program to make decisions and I asked you to write a program,
 
That has:
  1. A Listbox
  2. A Label next to the listbox labelling it "Colors"
  3. An array of colors: "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"
  4. A CommandButton labelled "Remove"
  5. A CommandButton labelled "Add"
  6. A CommandButton labelled "Find Missing"
  7. A CommandButton labelled "Find Duplicates"


The program should:

  1. Load the colors into the listbox
  2. When the user clicks on the "Remove" button , the selected color in the listbox is removed from the list.
  3. When the user clicks on the "Add" button, the selected color is added to the end (bottom) of the listbox.
  4. When the user clicks on the "Find Missing" button, the program should list all the missing colors in the listbox from the master set.
  5. When the user clicks on the "Find Duplicates" button, the program should list all the colors in the listbox that occur more than once.

 
Here's my take on the solution:

'-------------code starts here ' ' Article 10 ' OPTION EXPLICIT DIM Colors(7)' our color array '-------------- create our UI ' create a listbo SUB CreateMyListbox   ADDOBJECT "ListBox","MyListBox",120,10,100,120 ' leave        room for label   ' load the colors into the listbox...assumes you've set up the array first   MyListBox.AddItem Colors(1)   MyListBox.AddItem Colors(2)   MyListBox.AddItem Colors(3)   MyListBox.AddItem Colors(4)   MyListBox.AddItem Colors(5)   MyListBox.AddItem Colors(6)   MyListBox.AddItem Colors(7) END SUB
' create a label SUB CreateMyLabel   ADDOBJECT "Label","MyLabel",35,5,80,20 ' to the right        of the listbox   MyLabel.Caption = "Colors" END SUB
' create our Remove commandbutton SUB CreateRemoveCommandButton   ADDOBJECT "CommandButton","Remove",10,35,100,20   Remove.Caption = "Remove" END SUB
' create our Add commandbutton SUB CreateAddCommandButton   ADDOBJECT "CommandButton","Add",10,65,100,20   Add.Caption = "Add" END SUB

' create FindMissing commandbutton SUB CreateFindMissingCommandButton   ADDOBJECT "CommandButton","FindMissing",10,95,100,20   FindMissing.Caption = "Find Missing" END SUB

' create FindDuplicates commandbutton SUB CreateFindDuplicatesCommandButton   ADDOBJECT "CommandButton","FindDuplicates",10,125,100,20   FindDuplicates.Caption = "Find Duplicates" END SUB

'----------------event handlers ' Our Remove handler SUB Remove_click   ' remove the selected listbox item   MyListBox.RemoveItem MyListBox.ListIndex   ' MyListBox.ListIndex returns the number (array index) of the selected        item END SUB

' Our Add handler SUB Add_click   ' add the selected listbox item to the end of the listbox list   MyListBox.AddItem MyListBox.List(MyListBox.ListIndex)   ' MyListBox.List( ) returns the text in the list END SUB

' Find missing event handler SUB FindMissing_click   ' you probably got stuck trying to figure out how to do this... don't worry this was a trick problem. END SUB

' Find duplicates event handler SUB FindDuplicates_click   ' you probably got stuck trying to figure out how to do this... don't worry this was a trick problem. END SUB

'----------------main routines here ' set up our color array SUB SETUPCOLORS   Colors(1) = "Red"   Colors(2) = "Orange"   Colors(3) = "Yellow"   Colors(4) = "Green"   Colors(5) = "Blue"   Colors(6) = "Indigo"   Colors(7) = "Violet" END SUB

' set up our user interface SUB SETUPUI   CreateMyListBox   CreateRemoveCommandButton   CreateAddCommandButton   CreateFindMissingCommandButton   CreateFindDuplicatesCommandButton END SUB

SUB INITIALIZE   SETUPCOLORS ' this has to be done first because its used by CreateMyListBox   SETUPUI END SUB

SUB MAIN   INITIALIZE END SUB

MAIN ' our normal kickstart '-------------code ends here

Ok! I've left a couple of handlers empty because I think you would have a  hard time completing this exercise without having the benefit of this lesson.   Also, you'll notice that SETUPCOLORS and CreateMyListBox have code that's  repetitive. You load a bunch of stuff into an array or list. Wouldn't it be  nice to be able to simplify this? Well we can, and we do so using...

LOOPS  

    Your programs can not only make decisions, but they can do certain things      over and over again--sort of like deja vu. There are three basic types of  loops that you'll have to learn. One type is a "determinate" type.  This just means you always know how many times to repeat the loop. In NSBasic,  this loop is programmed using the FOR/NEXT statement. (There is also a nifty  other FOR EACH/NEXT command we'll go over next time.)
    The syntax for a FOR/NEXT command is:

    FOR counter = start TO end [STEP increment]
      ...your stuff....
    NEXT [counter] 
      
The loop is bracketed by the FOR and NEXT statements. And where "counter"  is a variable that keeps track of how many time you are about to go thru  the loop. "start" is the first value of "counter" when  the loop starts. The loop ends when "counter" executes the "end"th  iteration of the loop. Each time through the loop, "counter" is  incremented (or decremented) by "increment". Yup this seems confusing without an example. Here is a simple one: 

 FOR I = 1 TO 3
      MSGBOX I
 NEXT I 
This loop will show the MSGBOX 3 times (start = 1 end = 3) and each time  in the loop MSGBOX will show you the value of "counter". Now how  about counting from 1 to 10 but only displaying the odd numbers? Easy:

FOR I = 1 TO 10 STEP 2
      MSGBOX I
NEXT 
Each time through the loop, the "counter" value of I will get 2 (the "increment") added to it, so the loop only executes 5 times instead of 10, and only with the odd values from 1 to 10! Cool! Also, note that we didn't specify the "counter" in the NEXT statment. NEXT instead of NEXT I. Either is fine, but explicitly stating it is better style (documentation again).

      Now how about counting downward by 2s?


 FOR I = 10 TO 1 STEP - 2
      MSGBOX I
 NEXT I 
Always remember that "start" is always where you start, whether      you go up or down. Now you can also next loops (have one inside another. Try this:
   
 FOR I = 1 TO 3
      FOR J = 1 TO 3
     	 MSGBOX "I=" & I & " J=" & J
      NEXT J
 NEXT I 

That's all there is really to FOR statements, but they are powrerful when you know "start" and "end". But what happens when you  don't know? A good example is our last assignment.
We don't know how many colors the user deleted or how many duplicates exist. In that case, we use something known as an "indeterminate" loop. NSBasic has two types of indeterminate loops; the WHILE/WEND and the DO/LOOP.     
    The two loops are very similar, but they have two important differences. The      DO/LOOP always executes at least once, whereas the WHILE/WEND may not execute      at all. This is due to the other difference. The DO/LOOP executes at least      once because the check for whether the loop should loop is done at the end      of the loop,
    whereas the WHILE/WEND check is done at the beginning of the loop.
    The syntax of a DO/LOOP is:     


 DO
      ...your stuff inside the loop
 LOOP [WHILE|UNTIL condition]
     
and the WHILE/WEND     
 WHILE condition
      ...your stuff inside the loop
 WEND 
Let's take the example of counting from 1 to 10 again, but this time lets use indeterminate loops.
 I = 1
 DO
      MSGBOX I
      I = I + 1
 LOOP UNTIL I = 10 
   

Note that you have to handle the "counter" and the incrementing        of the counter. It doesn't happen like in the FOR/NEXT because NSBASIC doesn't        know the start or end points. In our assignment we could do something like:     

   
 I = 1
 DO
      Colors(I) = ...
      I = I + 1
 LOOP UNTIL I = 7   

We could also write this using the other variation of the DO/LOOP:

 I =1
 DO
      Colors(I) = ...
      I = I + 1
 LOOP WHILE I < 8 


Which one you use is really up to you, you can accomplish tasks either   way. Now the same thing using the WHILE/WEND: I = 1

WHILE I <= 7
      Colors(I) = ...
      I = I + 1
WEND 
Now I mentioned that DO/LOOPS always execute at least once and WHILE/WENDs  may note even execute. Here is an example:

 I = 2
 DO
      MSGBOX I
      I = I + 1
 LOOP UNTIL I = 3
 I = 1
WHILE I = 3       MSGBOX I       I = I + 1 WEND

   

True, this is a forced example, but it shows the point! Option Buttons Now for our widget of the day! The option button is like a checkbox. It  lets us toggle a value on and off, but unlike a checkbox, an option button  usually occurs in groups, and only one option button can be on at a time.  That is, turning one on, turns the others off.
There is nothing new about an OptionButton. You already know all the methods,  events, properties, and how to create one! The only problem we have to deal with is the exclusive nature of the button. If you create two buttons:


 ADDOBJECT "OptionButton","B1",10,10,100,20
 ADDOBJECT "OptionButton","B2",10,30,100,20
 ADDOBJECT "OptionButton","B3",10,50,100,20
 B1.Caption = "B1"
 B2.Caption = "B2"
B3.Caption = "B3"

and run it, you'll see that there is nothing inherently exclusive about the buttons! You can toggle them both on! This is a shortcoming in NSBasic,  since VisualBasic and other environments handle the exclusivitiy automatically. So what do we do? We have to write our own code to  handle option buttons. This is how: 
SUB B1_Click
      ' we know that B1 is now on, so we turn the others off...
      B2.Value = FALSE
      B3.Value = FALSE
END SUB
SUB B2_Click       B1.Value = FALSE       B3.Value = FALSE END SUB
SUB B3_Click       B1.Value = FALSE       B2.Value = FALSE END SUB


That's it for option buttons really.

   

For next time


For next time, rewrite the colors exercise to use loops to initialize the colors and the listbox. Next time we'll go over the FOR EACH/NEXT statement  and the PictureBox widget! Stay tuned!  Cheers!  
       
       
       
       
       

ARTICLE 7—STRINGS AND COMBOBOX

Programming Using NSBasicCEasicCE

ARTICLE 7—STRINGS AND COMBOBOX

All content (c)1999, 2002 Serg Koren.

All rights eserved.

Welcome to the seventh installment of NSBasicCE.

In this article we discuss strings and another user-interface widget, the ComboBox

Leftovers from Last Time

Last time we talked about variables and the CheckBo. I asked you to write a program that has:

  1. A command button labeled "Count"
  2. 2 CheckBox objects labeled "Left" and "Right"

The rogram should:

  1. Display a message box whenever the user taps on a check box. The message should display the name of the check box being tapped.
  2. Display a message showing the total number of times the user tapped eithr of the checkboxes.
  3. Use a variable to keep track of the number of times the user tapped either of the checkboxes.

Here is my version of the code. Again, yours may be different, but if it does what it’s supposed to, then you’ve done it correctly. However, it should e very similar with the major difference being the position of the widgets on the screen, and probably the ode style.

‘ -------start code here------------       
‘----------------------------         
' Article6 Assignment  
‘-----------------------------  
‘  
OPTION EXPLICIT ‘ remember this? See last article for more info  
DIM NumTaps    ‘ the number of times the checkboxes have been tapped. Note that this needs to be a global varable        (see last article)   
‘ ---------------- 
' UI Creation Routines  
‘ Create our Left checkbox  
SUB CreateLeftCheckbox  		
   ADDOBJECT “CheckBox”,”LeftCheckbox”,10,10,50,20 ‘ make our checkbox object  		
   LeftCheckbox.Caption = “Left	‘ set its label         
END SUB  
   
‘ Create our Right checkbox  
SUB CreateLeftCheckbox  		
   ADDOBJECT “CheckBox”,”RightCheckbox”,100,10,50,20 	‘ make our checkbox object  		
   RightCheckbox.Cation = “Right” ‘ set its label  
END SUB  
   
‘ Creat our Count CommandButton   
SUB CreateCountButton 		
   ADDOBJECT “CommandButton”,”CountButton”,50,50,50,20 	‘ create our button object  		
   CountButon.Caption = “Count” ‘ set its label  
END SUB  
   
‘----------------- Our event handlers        
‘ Display Left when the left checkbox is clicked 
SUB LeftCheckbox_Click  		
   MSGBOX “Left”,vbOKOnly,”Article6”  		
   NumTaps = NumTaps + 1  ‘ increment our counter  
END SUB  
   
‘ Display Right when the right checkbox is clicked         
SUB RightCheckbox_Click 		
   MSGBOX “Right”,vbOKOnly,”Article6”  		
   NumTaps = NumTaps + 1 ‘ increment our counter  
END SUB  
   
 ‘ Display the total number of times either check box was tapped 
SUB CountButton_Click  		
   MSGBOX NumTaps,vbOKOnly,”Article6”  
END SUB   

‘ ------------------- set up routines  
‘ Routine to create our user interface         
SUB SetupUI  		
  CreateLeftCheckbox     	
  CreateRightCheckbox     		
  CreateCountButton  
END SUB  
      
‘ Factored routine to set variables to initial values … it usually has more than just this in it  
SUB Initialization         		
  NumTaps = 0    ‘ make sure our counter is zeroed out         
END SUB  
  
‘ Our main subroutine  
SUB Main  
   SetupUI  
   Initialization ‘ set various variables to initial values  
END SUB  
 
Main ‘ our Immediate mode command to start everything         
‘---------------end code here   

The things to note about this program are that the NumTaps variable needs to be a global variable, otherwise we’ll get all sorts of errors.and a DIMension statement somewhere locally. Experment, and try this with your program to see what happens in both cases.

The other thing you probably tried to do (but couldn’t if you are brand new to programming) is you probably tried to have your CountButton message say something like “You tapped x times” or something simiar, but the best you could do is something similar to:

MSGBOX “You tapped”  
MSGBOX NumTaps  
MSGBOX “times.”


Of course when you tried this it didn't look right. This time around we talk abouthow you can do exactly wht you tried to do, and other things dealing with strings!

Strings


Earlier, we talked about variables and how variables stored and addresses and objects (which all came downers). So how do you store and manipulate text? In programming, when you talk about text that gets stored in variables and manipulated as they were variables are called "strings”. They are called strings because a piece of text that you store is treated as a “string of characters”. So what is a character? Well besides beinga letter, a character is also the smallest part of text that you can deal with. That means a character is the smallest piece of text that you can store in a variable. What’s the largest? You probably won’t have to worry about this--it’s that big. Ok, so that’s what we mean by the term “string” and chaacter.
So how do we store them in variables and use them?

To store a character in a variable, you simply treat it the same way that you would a number. Say we wanted to store the letter “A” into the variable MyCharacter:

  MyCharacter = “A” 

Note that we put the character (and all strings) in double-quotes. If we didn’t NSBasic would think we were trying to assign the value of the variable A into the variable MyCharacter. For example:

DIM , MyCharacter, MyOtherCharacter
A = 3
MyCharacter = A
MyOtherCharacter =“A”
MSGBOX MyCharacter
MSGBOX          MyOtherCharacter
MyCharacter = MyOtherCharacter ‘ move the value of MyOtherCharacter into MyCharacter  
   

If you ran the above code snippet, you’d see what I mean. Th thing you should note here is that although we called our variable MyCharacter, it actually stored a number. This should tell you that NSBasic doesn’t really care what you store in your variables or what you call them. It’s up to you to keep it all straight! Note that in other BASICs you will see variables with a $ after them such as, MyCharacter$. In these BASICs you can only store strings (and characters) in these variables, and you can’t store strings and characters in variables without the $. This actually makes it easier to keep things straight, but it makes for a tiny bit more typing on your part (the extra $).

So how about strings instead of characters? No problem! Use them the same way!

    
DIM MyString,          MyOtherString, MyThirdString
MyString = “Hello there,”
MyOtherString = “ how are you?”
MSGBOX MyString MSGBOX MyOtherString  
    
Neat huh?  You know more about using strings than you thought! Ok, so what about the question posed by our last assignment? How do we display something like “Hello there, how are you?” in one MSGBOX?  Well obviously you could just do: MSGBOX “Hello there, ho are you?”, but how do we tack pieces of strings together? “Tacking pieces of strings together” is called concatenating strings (or characters). 
You concatenate strings by using the & character between the pieces you want to tack together.  For instance, assume the above code; to concatenate MyString and MyOtherString you would do something like: 
MyThirdString = MyString & MyOtherString
MSGBOX MyThirdString 

Easy! And if you had a bunch of strings you wanted to piece together you just keep using the & to do it:

 String1 & String2 & String3 & …. 

Nothing tricky, here. So how do we tack on a number, say our NumTaps variable above? Exactly the same way! So if you wanted to display the message, “You tapped x times.” Instead of just the number, you could do this:

MSGBOX “You tapped “ & NumTaps & “ times.”        

Or you could assign everything to a variable and then just display the variable:

MyString = “You tapped “ & NumTaps & “ times.”
MSGBOX MyString 

So what happens if you try to concatenate to numbers instead of strings or chracters? Something like:

MSGBOX 2 & 3 

Try it! It actually works. And this should also tell you that you if you want spaces, you have to add spaces explicitly:

MSGBOX 2 & “ “ & 3 

So what’s going on? Concatenation only works with strings and characters; it doesn’t work with numbers! Well, behind the scenes, NSBasic is doing something (watch out more computer jargon coming) known as coercion or type casting. It sees that MSGBOX only displays strings, ad not numbers (don’t believe me, look up and read the page on MSGBOX in the manual again—the key phrase is “string expression?), and NSBasic says hey you’re giving me a number, so I better convert it to a string! So it does, and your MSGBOX works with numbers. Converting from one type of variable (a string say) to another type of variable (a number) is called coercion or type casting. Hm…I bet you’re thinking (if not, you should be) what happens if I try to get NSBasic to do coercio for something else, say addition:

MSGBOX 2 + “3” 

Yup, it works as you would expect. First thing that happens is that NSBasic coerces the character “3’ into the number 3, which it then added to the number 2 to get the number 5. But MSGBOX doesn’t work with numbers so it coerced the number 5 into the sring character &147;5”! Wow! Now if you’re truly evil (and we know you are) you like to screw things up and break them, so you say to yourself, “Self, I bet I can’t do this with non-numeric characters”, and you’d be correct:

MSGBOX 2 + “A” 

See what happens! You get a type-mismatch error, which tells you, you tried o do something with variable types that can’t be coerced properly. There’s no way to coerce the character “A” into a number that can be added to the numer 2 and get a meaningful number (well there is, but that’s another article.) You should be aware that not all BASICs are so easy to deal with. Some of them have special functions that explicitly coerce a number into a string and vice versa and force you to use them. That is, these BASICs don’t do automatic type casting.

Using strings, and coercion isn’t very hard to understand or use. It pretty much comes to common sense. So how do we take a string and break it up into smaller pieces? That’s what we’ll talk about next time, but now let’s look at our user-interface widget forthistime, the ComboBox.

ComboBox

A ComboBox is one of the more complicated widgets, but don’t panic. You already know a fair amount about it, how to create one, as well as what some of the properties, events, and methods do and how to use them. First of all, a ComboBox is a popup list of items. The user sees a line, he taps on it and it brings up list of items. He can then choose one of the items on the list. Your program then reacts to the choice the user made. Of course you can add, delete, and change the items in the list from within your program. Let’s go through the ComboBox systematically describing the new properties, methods, and events. New properties this time around includes FontName. This is the first time we’ve come across this. If you cross reference to the Properties page of the manual you find that FontName is a string! What does the string have? You can scour the maual and not find the anser. This depends partly on the hardware you run NSBasic on, and the fonts installed on the device. The string you would use is a name of one of these fonts. Another new property is IntegralHeight, which takes TRUE and FALSE for values. Most of the time you should set this to TRUE. What his does is make sure that the drop-down list is sized to an exact number of lines, so that it doesn’t show half an item (the top half). ListCount, another property is read-only (meaning you can’t set this, but you can assign it to a variable) and tells you how many items (choices) are in the popup list. ListIndex specifies which item in the list is selected (or picked by the user). Given our list of choices, we can have the program insert a new choice in the middle somewhere. The property NewIndex lets us do this by pointing to an item in the list where the new item will be inserted (all other items move down). Sorted is TRUE or FALSE, and specifies if the list of choices should be sorted alphabetically. The proprty Style that can beeither 0 or 2 (don’t ask about 1, that’s another story) and specifies whether the user can change the list by typing into it.

New methods include AddItem, which lets you specify a new choice to be added to the list, and the position its to be added into. For example:

Our ComboBox.AddItem “Inserted at 2”,2 

Wuld add the string “Inserted at 2”into the second slot in the list (all others move down.) Of course if the Sorted property is set, then the item will be inserted alphabetically no matter what index you specify for the second parameter. If you drop the “,2” at the end of the command, the string “Inserted at 2” would be inserted at the end of the list (unless again its sorted.) The Clear mthod will empty the list of choices so that there are none. The RemoveItem method is the opposite of the AddItem method. It lets us remove a choice at the index specified. For example:

 OurComboBox.RemoveItem 10 

removes the 10th item in the list of choices.

One hing you should be aware is that when we deal with indexes in NSBasic, the first item in any list is item 0 (instead of 1). Whereas humans start counting from 1, computers (usually) start counting from 0.

The onl new event we have to worry about is the DropDown event that gets triggered when the user drops the popup list (how’s that for a contradiction) down.

Combo boxes are really as complicated as the built-in user widgets get.

That’s enough for this time around. For next time, I want you to write a program that puts all of the things we’ve learned together. This is a bit more complex.

I want you to write a program that has:

1 – Five checkboxes. Each labeled with a number “1”, “2”, “3","4", “5

2 – A ComboBox

3 – A CommandButton labeled “+”

4 – A CommandButton labeled “-“

5 – A CommandButton labeled “Total”

6 – A CommandButton labeled “Clear”

The program should:

1 – Each time the usr checks a number checkbox put the number the user tapped at the end of the ComboBox list.

2 – If the user taps the + or – command button, ut a “+” or a “-“ at the end of the ComboBox list.

3 – If the user taps the “Total” command button, display the result of the items in the ComboBox using the message: “There are x items in the ComboBox.”

4 – If the user selects an item from the ComboBox, display the message: “The user chose: x.” (Note the period after the ‘x’.)

5 – If the user taps on the “Clear”command button, remove all entries from the ComboBox, and deselect (uncheck) all the checkboxes.

Next time, we'll go over breaking up Strings and talk about the Date object!

nsblogo2

ARTICLE 5--MSGBOXes, SUB and FUNCTION

Programming Using NSBasicCE

ARTICLE 5--MSGBOXes, SUB and FUNCTION

All content (c)1999, 2002 Serg Koren.

All rights reserved.

Welcome to the fifth installment of NSBasicCE.

This time we go over the another very common user-interface object you will use: MSGBOX.

Leftovers from Last Time

Last time we talked about CommandButtons and I asked you to write a program:

The program should have:

  1. Four command buttons.
  2. Each button should have a different label: Bold, Italic, Underline, and Normal

The program should:

  1. Start with all captions in the default style (not Bold, Underlined, or Italic)
  2. When you hit the button that says "Bold" the label style should go bold (stand out)
  3. When you hit the button that says "Italic" the label style should switch to italics
  4. When you hit the button that says "Underline" the label style should underline
  5. When you hit the button that says "Normal" all label styles should go normal (the default) and undo everything else.
  6. No button should affect any other button except for the "Normal" button which affects all the others.
  7. Use factoring.

If you're just starting out programming you may be overwhelmed by the amount of stuff you have to worry about all at once...don't worry! You don't have to worry about it all at once. Take one item and get is working. Then take another. And so on. This is the principle of divide-and-conquer. For instance, get just the Bold button working properly. Then copy the code from the Bold button and just change the lines you have to to get the Italic button working. And so on. This is mental factoring (as opposed to code factoring which we discussed earlier.) Never get overwhelmed by programming. It always just comes down to solving a tiny little problem and then adding on to it once its solved.

The hardest part of this assignment is the Normal button. The other three buttons just send a message to themselves; the Normal button sends a message to each of the other three buttons.

Here's my version of the program. First you'll notice that it doesn't look anything like yours. This doesn't mean mine is right and yours is wrong. If your program does what the assignment states, then you did it correctly. The most notable difference is probably the coordinates and size you used for the buttons (the last 4 parameters to the ADDOBJECT command). The other differences are due to something known as coding (programming) style. Religious wars have been fought over this and much blood has been shed. Coding style refers to how your code looks on the page. How pleasing to the eye is it. It also refers to how easy your code is to read and understand. Style amounts to how you space your lines, are your keywords (commands) in uppercase, lowercase, mixed case, do you have comments and how are they aligned, etc.

Of course, my coding style is the correct one.

'---start code here--- 
' 
'  A program that demonstrates the Font style capabilities of the CommandButton Object 
' -- Subroutines to create our buttons --- 
' A subroutine to create the Bold button 
SUB MakeBoldButton 	
   ADDOBJECT "CommandButton","MyBoldButton",10,10,70,30   	
   MyBoldButton.Caption = "Bold"   ' set the caption on the button to read "Bold" 
END SUB  

' A subroutine to create an Italic button 
SUB MakeItalicButton 	
   ADDOBJECT "CommandButton","MyItalicButton",10,50,70,30   	
   MyItalicButton.Caption = "Italic"  ' set the caption on the button to read "Italic" 
END SUB  

' A subroutine to create an Underline button 
SUB MakeUnderlineButton 	
   ADDOBJECT "CommandButton","MyUnderlineButton",10,90,70,30   	
   MyUnderlineButton.Caption = "Underline"  ' set the caption on the button to read "Underline" 
END SUB  

' A subroutine to create a Normal button 
SUB MakeNormalButton 	
   ADDOBJECT "CommandButton","MyNormalButton",10,130,100,30 
   MyNormalButton.Caption = "Norlaml"  ' set the caption on the button to read "Normal" 
END SUB 

 ' --- The Click event handler subroutines for our buttons ---
 ' The Bold Click Event handler 
SUB MyBoldButton_Click 	
   MyBoldButton.FontBold = True   ' make the caption bold 
END SUB  

' The Italic Click Event handler 
SUB MyItalicButton_Click   	
   MyItalicButton.FontItalic = True    ' make the caption italic 
END SUB  

' The Underline Click Event handler 
SUB MyUnderlineButton_Click   	
   MyUnderlineButton.FontUnderline = True   ' underline the caption 
END SUB  

' The Normal Click Event handler sends a message to the other 3 buttons 
SUB MyNormalButton_Click  	
   MyBoldButton.FontBold = False          ' turn bold style off   	
   MyItalicButton.FontItalic = False         ' turn italics off   	
   MyUnderlineButton.FontUnderline = False   ' turn underline style off 
END SUB  

' --- The UI setup SUBroutine --- 
SUB SetupUI   	
   MakeBoldButton   	
   MakeItalicButton   	
   MakeUnderlineButton   	
   MakeNormalButton
END SUB  

' --- Our main subroutine --- 
SUB Main   	
   SetupUI 
END SUB  Main ' Our one and only IMMEDIATE command 
'---end code here---


Not too bad! Ok, now you have a feel for how to use CommandButtons in your program. Remember, Objects can send messages to themselves, or to other Objects (like other CommandButtons). Now before we delve into our main topic, namely MSGBOXes, I want to talk a bit about something we've used but never really described. SUBroutines and FUNCTIONs.

SUB and FUNCTION

As we've mentioned SUBroutines and FUNCTIONs are ways of breaking up big hunks of code into reusable, easily managed, and understood pieces. We've seen and used SUBs before. They always consist of a matching pair of:

SUB 
...hunk of code here...
END SUB

where <name> is a name that you provide, that identifies this "hunk" of code. Whenever you want the subroutine to execute (run), you merely use its name. For instance in the CommandButton assignment we had a subroutine called SetupUI that created all our buttons. We got it to run in the Main subroutine by just using the name SetupUI. Very straightforward. And as the last line in the program shows we can call any subroutine from IMMEDIATE mode. Then why don't we call more from IMMEDIATE mode? It gets confusing and it's difficult to debug a program with lots of subroutine and function calls from IMMEDIATE mode, because you can't tell who calls what when easily.

Subroutines are easy. Functions are a little bit more complex, but they have more flexibility. Whereas subroutines just execute code, FUNCTIONs, not only execute a hunk of code, but they get an answer back to you. Huh? Think of it this way. Say you have a complex calculation to do:

5 x 5 x pi

(the area of a circle having radius 5).

And because you use it over and over and over in your main program, you decide to factor it out into its own subroutine:

SUB Area5
		Area = 5 * 5 * 3.14
END SUB
 

This would work fine, but what if you don't want to save it in the "Area" variable each time? Maybe someplace in your program you want to save it to a variable called "MyPoolSize" instead. You could have two separate subroutines. One called Area5 and one called AreaOfMyPool and store the first result in Area and the second in "MyPoolSize". But this gets cumbersome fast. That's where FUNCTIONs do wonders. FUNCTIONs return the value of a calculation (FUNCTIONs always return a value, SUBs never return a value) in the name of the function itself. For example:

FUNCTION AreaOfACircle
	AreaOfACircle = 5 * 5 * 3.14
END FUNCTION

First of all, a FUNCTION is like a SUB. It has a matching END FUNCTION statement. Also, you have to have a line (the very last one in the function usually) that uses the name of the function and assigns a value to it. You can have other code as well, but at least one line has to use the name of the function. (Don't worry NSBasic is smart enough to know that if it sees a value assigned to a name not to call the function again. So how does this help our pool problem? Well remember that a FUNCTON returns a value, and you have to put the value somewhere. So in our program we would have to assign the value (store the number) somewhere (a variable). So to call a FUNCTION you always have to assign its name to a variable like this:

AreaOfMyPool = AreaOfACircle

Of course you can do things like multiply the value by a number, add to it, etc.

AreaOfMyPool = AreaOfACircle * 2

But what happens if your pool doesn't happen to have a radius of 5 feet? That's where Parameters come in. Unless you've dealt with them the terminology can be confusing. Parameters are numbers you can pass into a SUB or FUNCTION that let you alter how the SUB or FUNCTION works. The confusing part is that there are two types of parameters (and I won't bore you with the jargon). The first is the type used as a placeholder in the SUB or FUNCTION itself. Using our circle again, we could define the function as:

FUNCTION AreaOfACircle(Radius)
AreaOfACircle = Radius * Radius * 3.14
END FUNCTION

Radius here is the placeholder parameter. The value we give Radius is passed into the function and replaces every occurrence of the word "Radius". That's the simplest way of thinking about it. So if Radius = 10 we would essentially execute:

10 * 10 * 3.14

So how do we pass a value to Radius? We use an actual parameter in the call to the function like so:

AreaOfMyPool = AreaOfACircle(10)

The number 10 in this statement is the actual parameter that is used for the value of the variable Radius in our Function call. We could get fancy (and often will with parameters) and pass in a variable like this:

RadiusOfMyPool	 = 10
AreaOfMyPool	 = AreaOfACircle(RadiusOfMyPool)

This is considered better coding style, since you know what the 10 really stands for--the radius of my pool.

Of course, you can have more than one parameter. Say you have a rectangular pool:

FUNCTION AreaOfARectangle(Height,Width)
AreaOfARectangle = Height * Width
END FUNCTION
HeightOfMyPool = 100
WidthOfMyPool = 10
AreaOfMyPool = AreaOfARectangle(HeightOfMyPool,WidthOfMyPool)

When using more than one parameter, the FUNCTION call itself has to have a place holder for each parameter, and the call to the function has to have a value for each parameter. Just separate them with a comma.

Ok, how would you use parameters with a SUB? The same way, but remember a subroutine doesn't return a value, so whatever you do gets done in the subroutine:

SUB FigureOutTheAreaOfMyPool(Width,Height)
	AreaOfMyPool = AreaOfARectangle(Width,Height)
END SUB
 
Width = 10
Height = 10
FigureOutTheAreaOfMyPool Width,Height

A couple of things to note here. First, parameters themselves can be parameters (Width, Height in the definition of FigureOutTheAreaOfMyPool). Also, the call to the SUB with parameters doesn't use the parentheses around the parameters:

CallASub param1, param2
CallAFunction(param1,param2)

So, what is our ADDOBJECT,"CommandButton",<name>,....? It's a subroutine, and not a function. One that's been written for you and you don't have to worry about what's inside, but still a puny little sub like ours.

There are other types of parameters that a SUB or FUNCTION can use, but we'll discuss those in the future. Now we'll talk about another FUNCTION (built-into NSBasic), namely the MSGBOX.

MSGBOX

The MSGBOX manual page is misleading. It's called a FUNCTION (you can tell by the parameters in parentheses). However it's also a SUB. MSGBOX displays a dialog box with some buttons and lets the user make a decision or just displays a message to the user. It's very flexible and has lots of options (that you set with parameters). We've used a simple one before:

MSGBOX "Hello there!"

You can change the look of the MSGBOX by adding buttons. A list of buttons is shown in the manual. You would use the value for the buttons parameter after the string (called the prompt in the manual):

MSGBOX "Hello there!",5
or
MSGBOX "Hello there!",vbRetryCancel

You can use either the Constant or the Value, it doesn't matter. But using the Constant name reminds you of the buttons. vbRetryCancel is more informative than 5. It's a matter of style.

The final parameter, "title" puts a title, where else but, in the title bar of the dialog:

MSGBOX "Hello there!",vbRetryCancel,"A Silly MSGBOX"

The above are all used as if MSGBOX is a subroutine...no parentheses, and we don't get a value. You can test to see what button the user tapped:

ButtonTapped = MSGBOX("Hello there!",vbRetryCancel,"A Silly MSGBOX")

Note the parens, and we're assigning the value of MSGBOX back to ButtonTapped. It's a function here. MSGBOX is weird because its one of the few (if not only) things in NSBasic that acts like both a function and a subroutine. Try:

MSGBOX("Hello there",vbOkOnly)

and see what error you get. This tells you that you're trying to use MSGBOX like a subroutine (you're not assuaging it to a variable), but you're still using parentheses. So NSBasic says its really a SUB and you can't have the parentheses. Ack! This is one of the most confusing error messages in NSBasic; just remove the parentheses, or assign it to a variable like we did before to get rid of the error.

Ok, now if you followed that we'll try something tricky. This is called a nested call. A nested call is one call right inside another (like a bird's nest). Easy homework for next time!

Explain what the following does:

MSGBOX MSGBOX("My homework!",vbYesNoCancel,"Homework "),vbOKOnly,"My MSGBOX homework"

a) How many functions are there?

b) How many subroutines are there?

c) What gets called/executed first, the subroutine, or the function?

d) When you run this line, what is that number that pops up? Run it again and try something else.

e) How many parameters does this line have?

Next time we'll talk more about variables (and really explain them instead of just talking about them) and go over another Object, the CheckBox! Stay tuned!

If you get stuck or have a question about anything we've gone over, feel free to e-mail me at Serg@VisualNewt.com

Cheers!

nsblogo2
©2008, 2009, 2010 Serg Koren & VisualNewt Software.  All rights reserved.