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

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