For Chapter 12, we're now delving into the area of writing our own classes. We've been using the Visual Basic Studio pre-written classes for everything up to this point.
Classes are the structures/foundations of a program where data types/objects are declared, stored, and processed. Each classes has its own set of controls, properties, functions, procedures, variables, etc.
The purpose of writing our own class is to access different private variables outside of class by only accessing certain public properties that we set the parameters to. We did an example of this in class, for the purpose of using the example of giving money to another person. You don't give the random person access to your home, your safe, your safe combo, and an unsupervised gateway to your stashed money. Instead, you go retrieve the money and deliver the money yourself to the person. Much in the same case, we can add a new class, use the Get...Set method, and retrieve different sets of data between classes while still keeping the rest of the date private.
To do this, click Project, then Add Class. Like a form, this only creates a blueprint of the class. To create an instance of the class, declare it within the code. Any variable you've entered in the new class, if set to private, won't be accessable outside the class. Setting the variables to public isn't safe, so in this case we must use a Public Property procedure.
Format:
Public Property PropertyName() As String
Get
Statements
End Get
Set (ByVal value As String)
Statements
End Set
End Property
Example:
Public Property Name() As String
Get
return strname
Set (ByVal value As String)
If value<>nothing then
strname=value
When this is accessed by another class, it'll first set the value of the variable strName to whatever is stored in the variable in the class. When this is called in the other class, it'll then use the get procedure to retrieve only the stored value, which in this case is the name. I'll add more tomorrow.
BUS 092
Wednesday, April 27, 2011
Monday, April 18, 2011
Chapter 8 Summary
8.1 Arrays
-Arrays are "like groups of variables with one name". They are stored within an array and are called by using a subscript (known as an index).
The basic format for an array is: Dim ArrayName (UpperSubscript) As Datatype
-As you can see, it's very similar to the declaration of your simple variable, but notice the parantheses for the upper subscript. The subscript is used to declare how many values are stored in the array. The subscript starts at an index of 0, just like a counter in a loop, so keep that in mind.
Example: Dim IntegerArray (10) As Integer will declare an array that can hold 11 values (0-10).
-Arrays work well within loops to store a large number of values into an array quickly and easily without having to write out individual statements.
Example:
Dim IntegerArray (10) As Integer
Dim intCount as Integer
For intCount=0 to IntegerArray
IntegerArray(intCount)=100
Next
This will put the value of 100 into every value position index in the array. You can also use input boxes to store values in an array.
-Arrays can throw exceptions when an array is called using an index that is "out of range". Make sure to double check code during design time.
-To get the length of an array, make sure to remember that the "length" function is set at a range starting at 1, not 0 like an array. Make sure to use arrayName.length-1 to set the correct range.
-You can use array values just like variables, just make sure you're calling the right value you're looking for.
Example: IntegerArray(2) *50. <---This take the 3rd index value in the array and multiplies it by 50.
For Each Loop
-Special loop to simplify array processing when you need to retrieve the value of each element. This loop cannot modify array values, just read them.
For Each var As type In array
statements
Next
var-name of variable that will be created for use with the loop.
type-data type of the array
array-name of the array.
-These loops will iterate once for every value in the array. Each loop it'll store a copy of the array elements into the variable you just created.
Book Example: Dim intArray() As Integer={10,20,30,40,50,60}
For Each intVal As Integer In intArray
lstShow.Items.Add(intVal)
Next
What this does is declare the "intVal" variable that will store the copies of the elements in the array intArray. The first time this loop executes, it'll copy what is in the 0 position of intArray into the 0 position of intVal. It'll do this for all positions in the index, and it'll add them to their respective positions in the list box (the 0 position copied in intVal, in this case 10, will be put in the 0 position in the list box and so forth).
8.2 More About Array Processing
-You can total the values in a numeric array using a For Next loop.
For intcount=0 to intUnits.length-1
intTotal+=intUnits(intCount)
Next
-You can also find the average by adding up all the values like in the last example and then dividing that number by the length of the array.
-You can search through an array using the sequential search method.
-To sort an array, use the Array.Sort method. Array.Sort(ArrayName)
Example: Dim intNumbers() As Integer={7,12,1,6,3}
Array.Sort(intNumbers) will sort the array into 1,3,6,7,12
-To change the amount of elements in an array at runtime, use the ReDim statement
ReDim [Preserve] ArrayName (UpperSubscript)
Preserve-optional keyword, if used any existing values in the array are preserved. If it's not used, existing values in the array are destroyed.
ArrayName-name of the array being resided.
UpperSubscript-new index of the array
8.3 Procedures/Functions and Arrays
-You can use arrays in procedures/functions.
8.4 Multidimensional Arrays
-Like an array of arrays. It can be used to hold multiple sets of values.
A square 3x4 has 12 squares total. A Multi-dimensional array with this square would be declared as
Dim dblScores (2,3) As Double.
(2,3)-the subscript for the array. Since arrays start at a value of 0, the rows are now 2 (0-2) and the columns 3 (0-3).
8.5 GUI Design
Enabled property: When set to false, whatever control is disabled and can't receive the focus/respond to events. Controls may appear "dimmed". Default, it is set to true.
Timer control: Allows an application to automatically execute code at regular time intervals. This is based in milliseconds.
Timer Events: You can create event handlers that respond to timer ticks.
Control Properties: When enabled is set to true, the timer control will respond to tick events. The interval property is the number of milliseconds that elapse between timer events. An interval property of 1,000 means that every second will result in a tick event as 1000 ms=1 second.
8.6 GUI Design
Anchor Property: When a control is anchored to a form's edge, it'll resize if the application is resized in runtime.
Dock Property: When a control is docked, it is positioned directly against a form edge. The length/width of the control is changed to match the length/width of the form edge.
-Arrays are "like groups of variables with one name". They are stored within an array and are called by using a subscript (known as an index).
The basic format for an array is: Dim ArrayName (UpperSubscript) As Datatype
-As you can see, it's very similar to the declaration of your simple variable, but notice the parantheses for the upper subscript. The subscript is used to declare how many values are stored in the array. The subscript starts at an index of 0, just like a counter in a loop, so keep that in mind.
Example: Dim IntegerArray (10) As Integer will declare an array that can hold 11 values (0-10).
-Arrays work well within loops to store a large number of values into an array quickly and easily without having to write out individual statements.
Example:
Dim IntegerArray (10) As Integer
Dim intCount as Integer
For intCount=0 to IntegerArray
IntegerArray(intCount)=100
Next
This will put the value of 100 into every value position index in the array. You can also use input boxes to store values in an array.
-Arrays can throw exceptions when an array is called using an index that is "out of range". Make sure to double check code during design time.
-To get the length of an array, make sure to remember that the "length" function is set at a range starting at 1, not 0 like an array. Make sure to use arrayName.length-1 to set the correct range.
-You can use array values just like variables, just make sure you're calling the right value you're looking for.
Example: IntegerArray(2) *50. <---This take the 3rd index value in the array and multiplies it by 50.
For Each Loop
-Special loop to simplify array processing when you need to retrieve the value of each element. This loop cannot modify array values, just read them.
For Each var As type In array
statements
Next
var-name of variable that will be created for use with the loop.
type-data type of the array
array-name of the array.
-These loops will iterate once for every value in the array. Each loop it'll store a copy of the array elements into the variable you just created.
Book Example: Dim intArray() As Integer={10,20,30,40,50,60}
For Each intVal As Integer In intArray
lstShow.Items.Add(intVal)
Next
What this does is declare the "intVal" variable that will store the copies of the elements in the array intArray. The first time this loop executes, it'll copy what is in the 0 position of intArray into the 0 position of intVal. It'll do this for all positions in the index, and it'll add them to their respective positions in the list box (the 0 position copied in intVal, in this case 10, will be put in the 0 position in the list box and so forth).
8.2 More About Array Processing
-You can total the values in a numeric array using a For Next loop.
For intcount=0 to intUnits.length-1
intTotal+=intUnits(intCount)
Next
-You can also find the average by adding up all the values like in the last example and then dividing that number by the length of the array.
-You can search through an array using the sequential search method.
-To sort an array, use the Array.Sort method. Array.Sort(ArrayName)
Example: Dim intNumbers() As Integer={7,12,1,6,3}
Array.Sort(intNumbers) will sort the array into 1,3,6,7,12
-To change the amount of elements in an array at runtime, use the ReDim statement
ReDim [Preserve] ArrayName (UpperSubscript)
Preserve-optional keyword, if used any existing values in the array are preserved. If it's not used, existing values in the array are destroyed.
ArrayName-name of the array being resided.
UpperSubscript-new index of the array
8.3 Procedures/Functions and Arrays
-You can use arrays in procedures/functions.
8.4 Multidimensional Arrays
-Like an array of arrays. It can be used to hold multiple sets of values.
A square 3x4 has 12 squares total. A Multi-dimensional array with this square would be declared as
Dim dblScores (2,3) As Double.
(2,3)-the subscript for the array. Since arrays start at a value of 0, the rows are now 2 (0-2) and the columns 3 (0-3).
8.5 GUI Design
Enabled property: When set to false, whatever control is disabled and can't receive the focus/respond to events. Controls may appear "dimmed". Default, it is set to true.
Timer control: Allows an application to automatically execute code at regular time intervals. This is based in milliseconds.
Timer Events: You can create event handlers that respond to timer ticks.
Control Properties: When enabled is set to true, the timer control will respond to tick events. The interval property is the number of milliseconds that elapse between timer events. An interval property of 1,000 means that every second will result in a tick event as 1000 ms=1 second.
8.6 GUI Design
Anchor Property: When a control is anchored to a form's edge, it'll resize if the application is resized in runtime.
Dock Property: When a control is docked, it is positioned directly against a form edge. The length/width of the control is changed to match the length/width of the form edge.
Monday, March 21, 2011
Chapter 7 Summary
7.1 Multiple Forms
-We've only dealt with using one form so far. You can use several forms within a program. The StartUp form is the one form that is automatically displayed when the program executes.
Form Files/Form Names
-Name is stored in form's Name property. When a form is created, the code associated with the form is stored in a file that has the same name followed by a .vb extension. This is in the Solutions Explorer window.
-To rename an existing form, you can do two things. If you change the form's file name within the Solution Explorer window, it'll also rename the form. However, if you just change the form name in the Name property, the form's file name doesn't change automatically.
-To add a new form to a project, click Project on the menu bar followed by Add Windows Form...
-To switch between forms during design time, double-click on the form's entry in the Solution Explorer window.
-You can designate the StartUp form in the Solution Explorer window by going to each form property.
-To remove a form/delete the file, right click/delete in Solution Explorer
-If you just want to remove a form from the current project but don't want to delete the actual file,
-right click the form in Solution Explorer/press exclude from project
-A form's class declaration (Public Class formname End Class) doesn't create a form, but is merely a blue-print.
To display a form, create an instance of the form:
-Dim ObjectVAriable As New ClassName
Example:
Dim frmError As New ErrorForm
-frmError is the variable that is declared.
-ErrorForm is the instance of the ErrorForm form that is created in memory.
NOTE: This statement doesn't cause the form to be displayed on the screen, it only creates an instance of the form in memory and assigns its address to the variable declared. You need to use the object variable to execute form methods.
Displaying a Form
-Forms can either be modal or modeless.
-Modal: when a modal form is displayed, no other form in the capplication can receive focus until this form is closed. User must close this form before they can interact with other forms.
-Modeless: allows user to switch focus to another form while it is displayed.
ShowDialog Method: causes form to be dsiplayed as a modal form.
Show Method: causes form to be displayed as a modeless form.
Examples: frmError.ShowDialog()-Modal; frmError.Show()-Modeless.
-To close a form, use the Close Method, like we've been using. Me.Close(). Causes the current executing form to close.
Hide Method: makes a form/control invisible, but it isn't removed from memory. Has same effect as setting visible property to FALSE. Use Me.Hide()
Load, Activated, FormClosing, and FormClosed Events
-Load Event: statements to be executed when the form initially loads.
-Activated Event: occurs when user switches focus to the form from another form/application.
-FormClosing Event: occurs when a form is in the process of closing, but before it has actually closed. You can use a FormClosing event handler to for instance ask the user if they really want to quit.
-FormClosed Event: occurs after a form has closed. Code to be executed immediately after a form has closed.
-To access controls on a different form, you can access them by calling them in code.
Example: Application has a form named "GreetingsForm"/on GreetingsForm there is a lbl called lblMessage.
Dim frmGreetings As New GreetingsForm
frmGreetings.lblMessage.Text="Good day!"
frmGreetings.ShowDialog()
This first creates an instance of GreetingsForm and assigns it to frmGreetings variable. the "frmGreetings." that precedes the lblMessage.Text command tells you that the form isn't the current form. The ShowDialog() will call the form's method to display the form on the screen.
Class-Level Variables
-Class level variables on one form are accessible anywhere in that form one form, but they are not accessible by default to statements outside the form file.
-To make a class-level variable available to methods outside the class, use the Public keyword.
-Remember, the AccessSpecifier is automatically set to "Public" if none is given. Remember to use the correct "Public" or "Private" keyword depending on your intention of use.
7.2 Modules
-A VB file that contains only code (procedures, functions, and declarations of variables/constants).
-These appear in the Solution Explorer when created, with a .vb extension.
-Ideal for calling the same function/procedure over several different forms.
-Format is:
Module ModuleName (this should contain "module" at the end of the name for easy reference)
[Module Conters]
End Module
-To add a module, click Project and then Add Module.
-Variables declared inside a module, but not inside a procedure/function, is a module-level variable.
-These are accessible to any procedure/function in the module.
-If "Dim" or "Private" keywords are used, the variable is not accessible to statements outside the module.
-If "Public" is used, it is accessible to statements outside the module. (known as a "global variable"
-You can add a module that you've already created to future projects by using the Project-Add Existing Item selection in the menu bar.
7.3 Menus
-Menu system: collection of commands organized in one or more drop-down menus.
-Menu designer: allows you to visually create a custom menu system for any form in an application.
See book example pg. 439 for the screenshots.
-Menu Names: each drop-down menu has a name.
-Menu Command: User selects a command by clicking it, entering access key, or shortcut key.
-Shortcut Key: key/combination of keys that cause a menu command to execute.
-Disabled menu command: cause a menu command to be disabled when you don't want user to select it.
-Checked menu command: usually one that turns an option on/off.
-Submenu:Some commands on a menu are actually names of submenus. These are characterized by a right arrow next to the command.
-Separator Bar: horizontal bar used to separate groups of commands.
MenuStrip Control
-To construct a menu, use this control.
-Everytime you add an item to a menu, you create a ToolStripMenuItem object.
-Use the Menu Designer to create menu items.
-Every ToolStripMenuItem object you create in a menu is given the same default names like all other controls and can be changed in the properties window.
Explore the properties window for all the various things you can do with menus.
-To insert a menu item above an existing menu item, start the menu designer/right-click the existing menu item/select insert and then MenuItem.
-To delete a menu item, right click the menu item to delete, select delete.
-To rearrange menu items, simply click/drag.
-You don't need to write code to display a menu/submenu. If a menu item has a menu/submenu to display, VB will display it automatically.
-If a menu item doesn't have a menu/submenu to display, use a click event handler.
7.4 Building the high Adventure Travel Agency Price Quote Application
-See book, starting pg. 451.
-We've only dealt with using one form so far. You can use several forms within a program. The StartUp form is the one form that is automatically displayed when the program executes.
Form Files/Form Names
-Name is stored in form's Name property. When a form is created, the code associated with the form is stored in a file that has the same name followed by a .vb extension. This is in the Solutions Explorer window.
-To rename an existing form, you can do two things. If you change the form's file name within the Solution Explorer window, it'll also rename the form. However, if you just change the form name in the Name property, the form's file name doesn't change automatically.
-To add a new form to a project, click Project on the menu bar followed by Add Windows Form...
-To switch between forms during design time, double-click on the form's entry in the Solution Explorer window.
-You can designate the StartUp form in the Solution Explorer window by going to each form property.
-To remove a form/delete the file, right click/delete in Solution Explorer
-If you just want to remove a form from the current project but don't want to delete the actual file,
-right click the form in Solution Explorer/press exclude from project
-A form's class declaration (Public Class formname End Class) doesn't create a form, but is merely a blue-print.
To display a form, create an instance of the form:
-Dim ObjectVAriable As New ClassName
Example:
Dim frmError As New ErrorForm
-frmError is the variable that is declared.
-ErrorForm is the instance of the ErrorForm form that is created in memory.
NOTE: This statement doesn't cause the form to be displayed on the screen, it only creates an instance of the form in memory and assigns its address to the variable declared. You need to use the object variable to execute form methods.
Displaying a Form
-Forms can either be modal or modeless.
-Modal: when a modal form is displayed, no other form in the capplication can receive focus until this form is closed. User must close this form before they can interact with other forms.
-Modeless: allows user to switch focus to another form while it is displayed.
ShowDialog Method: causes form to be dsiplayed as a modal form.
Show Method: causes form to be displayed as a modeless form.
Examples: frmError.ShowDialog()-Modal; frmError.Show()-Modeless.
-To close a form, use the Close Method, like we've been using. Me.Close(). Causes the current executing form to close.
Hide Method: makes a form/control invisible, but it isn't removed from memory. Has same effect as setting visible property to FALSE. Use Me.Hide()
Load, Activated, FormClosing, and FormClosed Events
-Load Event: statements to be executed when the form initially loads.
-Activated Event: occurs when user switches focus to the form from another form/application.
-FormClosing Event: occurs when a form is in the process of closing, but before it has actually closed. You can use a FormClosing event handler to for instance ask the user if they really want to quit.
-FormClosed Event: occurs after a form has closed. Code to be executed immediately after a form has closed.
-To access controls on a different form, you can access them by calling them in code.
Example: Application has a form named "GreetingsForm"/on GreetingsForm there is a lbl called lblMessage.
Dim frmGreetings As New GreetingsForm
frmGreetings.lblMessage.Text="Good day!"
frmGreetings.ShowDialog()
This first creates an instance of GreetingsForm and assigns it to frmGreetings variable. the "frmGreetings." that precedes the lblMessage.Text command tells you that the form isn't the current form. The ShowDialog() will call the form's method to display the form on the screen.
Class-Level Variables
-Class level variables on one form are accessible anywhere in that form one form, but they are not accessible by default to statements outside the form file.
-To make a class-level variable available to methods outside the class, use the Public keyword.
-Remember, the AccessSpecifier is automatically set to "Public" if none is given. Remember to use the correct "Public" or "Private" keyword depending on your intention of use.
7.2 Modules
-A VB file that contains only code (procedures, functions, and declarations of variables/constants).
-These appear in the Solution Explorer when created, with a .vb extension.
-Ideal for calling the same function/procedure over several different forms.
-Format is:
Module ModuleName (this should contain "module" at the end of the name for easy reference)
[Module Conters]
End Module
-To add a module, click Project and then Add Module.
-Variables declared inside a module, but not inside a procedure/function, is a module-level variable.
-These are accessible to any procedure/function in the module.
-If "Dim" or "Private" keywords are used, the variable is not accessible to statements outside the module.
-If "Public" is used, it is accessible to statements outside the module. (known as a "global variable"
-You can add a module that you've already created to future projects by using the Project-Add Existing Item selection in the menu bar.
7.3 Menus
-Menu system: collection of commands organized in one or more drop-down menus.
-Menu designer: allows you to visually create a custom menu system for any form in an application.
See book example pg. 439 for the screenshots.
-Menu Names: each drop-down menu has a name.
-Menu Command: User selects a command by clicking it, entering access key, or shortcut key.
-Shortcut Key: key/combination of keys that cause a menu command to execute.
-Disabled menu command: cause a menu command to be disabled when you don't want user to select it.
-Checked menu command: usually one that turns an option on/off.
-Submenu:Some commands on a menu are actually names of submenus. These are characterized by a right arrow next to the command.
-Separator Bar: horizontal bar used to separate groups of commands.
MenuStrip Control
-To construct a menu, use this control.
-Everytime you add an item to a menu, you create a ToolStripMenuItem object.
-Use the Menu Designer to create menu items.
-Every ToolStripMenuItem object you create in a menu is given the same default names like all other controls and can be changed in the properties window.
Explore the properties window for all the various things you can do with menus.
-To insert a menu item above an existing menu item, start the menu designer/right-click the existing menu item/select insert and then MenuItem.
-To delete a menu item, right click the menu item to delete, select delete.
-To rearrange menu items, simply click/drag.
-You don't need to write code to display a menu/submenu. If a menu item has a menu/submenu to display, VB will display it automatically.
-If a menu item doesn't have a menu/submenu to display, use a click event handler.
7.4 Building the high Adventure Travel Agency Price Quote Application
-See book, starting pg. 451.
Friday, March 18, 2011
Chapter 6 Summary
6.1 Procedures
-Collection of statements that performs a task.
-Unlike a function, procedures don't return a value.
Use the call method to call procedures.
Modularize: breaking apart code into smaller procedures.
Format:
[Access Specifier] Sub ProcedureName ([parameterList])
[Statements]
End Sub
-When making a variable local to a procedure, that variable will be destroyed once the procedure executes. If you want to keep that variable, use "Static" instead of "Dim" when declaring the variable.
6.2 Passing Arguments to Procedures
-Values that are passed to a procedure to execute are called arguments.
ByVal: passing an argument using this means that it's only a copy of the argument, the original argument isn't changed from what the ByVal statement brings back.
ByRef: is the original argument, changes can be made.
Example of how to pass arguments:
Sub DisplayValue (ByVal intnumber As Integer)
MessageBox.Show(intNumber.ToString())
End Sub
The name of the procedure is "DisplayValue". "intNumber" is the variable that is created to store the value that the code passes the argument to. If the code were to be:
DisplayValue(txtPhone.text); it'll pass whatever is in the text-box to the intNumber variable, eventually displaying a message box with the text-box.
-You can pass multiple arguements to a procedure, just make sure you have enough variables.
6.3 Functions
-A function returns a value to the part of the program that called the function.
Format:
[AccessSpecifier] Function FunctionName ([ParameterList]) As DataType
[Statements]
Return Value
End Function
Example:
Function Sum(ByVal dblNum1 As Double, ByVal dblNum2 As Double) As Double
Return dblNum1+dblNum2
End Function
In this function, you're declaring a Function name as "Sum". dblNum1/dblNum2 will be the variables to hold the user input. The "As Double" after the parantheses is the data type that the function will return the value as.
If the code was: dblTotal=Sum(dblVal1+dblVal2), it'll pass the dblVal1/dblVal2 variables to the dblNum1/dblNum2 variables in the function. It'll return a value, and Sum will assign that value to the dblTotal variable.
6.4 Debugging Continued
Step Into: When an application is break mode, step into causes the currently highlighted line to execute.
-Activate by pressing F8, select Debug in the menu-Step Into, or click the Step Into button.
Step Over: It'll cause the currently highlighted line to execute like Step Into, but if the line contains a function/procedure, it'll execute the function/procedure without stopping through it's statements.
-Activate by pressing Shit+F8, select Step Over from Debug, or press the Step Over button.
Step Out: Use this when single-stepping through a function/procedure if you want the remainder of the function/procedure to finish executing without single-stepping.
-Activate by pressing Ctrl+Shift+F8, select Step Out from Debug, or press Step Out button.
6.5 Bagel/Coffee Price Calculator Application
See book starting pg. 381.
-Collection of statements that performs a task.
-Unlike a function, procedures don't return a value.
Use the call method to call procedures.
Modularize: breaking apart code into smaller procedures.
Format:
[Access Specifier] Sub ProcedureName ([parameterList])
[Statements]
End Sub
-When making a variable local to a procedure, that variable will be destroyed once the procedure executes. If you want to keep that variable, use "Static" instead of "Dim" when declaring the variable.
6.2 Passing Arguments to Procedures
-Values that are passed to a procedure to execute are called arguments.
ByVal: passing an argument using this means that it's only a copy of the argument, the original argument isn't changed from what the ByVal statement brings back.
ByRef: is the original argument, changes can be made.
Example of how to pass arguments:
Sub DisplayValue (ByVal intnumber As Integer)
MessageBox.Show(intNumber.ToString())
End Sub
The name of the procedure is "DisplayValue". "intNumber" is the variable that is created to store the value that the code passes the argument to. If the code were to be:
DisplayValue(txtPhone.text); it'll pass whatever is in the text-box to the intNumber variable, eventually displaying a message box with the text-box.
-You can pass multiple arguements to a procedure, just make sure you have enough variables.
6.3 Functions
-A function returns a value to the part of the program that called the function.
Format:
[AccessSpecifier] Function FunctionName ([ParameterList]) As DataType
[Statements]
Return Value
End Function
Example:
Function Sum(ByVal dblNum1 As Double, ByVal dblNum2 As Double) As Double
Return dblNum1+dblNum2
End Function
In this function, you're declaring a Function name as "Sum". dblNum1/dblNum2 will be the variables to hold the user input. The "As Double" after the parantheses is the data type that the function will return the value as.
If the code was: dblTotal=Sum(dblVal1+dblVal2), it'll pass the dblVal1/dblVal2 variables to the dblNum1/dblNum2 variables in the function. It'll return a value, and Sum will assign that value to the dblTotal variable.
6.4 Debugging Continued
Step Into: When an application is break mode, step into causes the currently highlighted line to execute.
-Activate by pressing F8, select Debug in the menu-Step Into, or click the Step Into button.
Step Over: It'll cause the currently highlighted line to execute like Step Into, but if the line contains a function/procedure, it'll execute the function/procedure without stopping through it's statements.
-Activate by pressing Shit+F8, select Step Over from Debug, or press the Step Over button.
Step Out: Use this when single-stepping through a function/procedure if you want the remainder of the function/procedure to finish executing without single-stepping.
-Activate by pressing Ctrl+Shift+F8, select Step Out from Debug, or press Step Out button.
6.5 Bagel/Coffee Price Calculator Application
See book starting pg. 381.
Saturday, March 12, 2011
Chapter 5 Summary
5.1 Input Boxes
-A simple/quick way to ask a user to enter data. An input box displays a message and allows the user to enter input into a text-box. The box also has Ok/Cancel buttons.
-Use the InputBox function:
InputBox(Prompt [, Title] [, Default] [, Xpos] [, Ypos])
-Title is a string that appears in the input box's title bar.
-Default is the string initially displayed in the text-box when it first displays.
-Xpos/Ypos determine where the input box will be displayed on the screen.
-Prompt is the text you designate to be in the input box as a label.
5.2 List Boxes
-Displays a list of items and also allows users to select the items in the list.
-When a list box contains more items than can be displayed, a scroll bar will appear in the list box.
Items Property:
-Entries in the list box are stored in the property named Items. You can store values in the Item Property using the String Collection Editor.
Items.Count Property:
-Use this to determine the number of items stored in the list box. When no items are in the Items property, the Items.Count property=0.
Item Indexing:
-The first item in a list box collection has the value of "0", like in a string. Always think of "n-1" to get the last index value, where "n" is the actual number of items in the collection.
-To access the items in code, use something like: lstEmployees.Items (0), where 0 is the first object stored.
-If you want to assign an value in a list box to a variable, remember to convert it to the appropriate format (Using the CInt for an integer, .ToString( ) for string, etc).
-Use try and catch statements to handle exceptions caused by out of range values.
SelectedIndex Property:
-When the user selects an item in a list box, the index of the item is stored in the SelectedIndex property.
-When no item is selected, the SelectedIndex=-1.
SelectedItem Property:
-SelectedIndex contains index of the currently selected item. SelectedItem contains the item itself.
-Example: List box "lstFruit" contains Apples, pears, bananas. If the user has selected pears, the following statement copies the string pairs to variable strSelectedFruit:
strSelectedFruit=lstFruit.SelectedItem.ToString()
Sorted Property:
-Use this to alphabetize the items in the Items property. This is set to False by default. Set it to True to alphabetize.
Items.Add Method:
-To store values in Item property in realtime, use Items.Add.
ListBox.Items.Add (Item)
-List box=name of control
-Item=value to be added to Items property
Items.Insert Method:
-Insert an item at a specific position using the Items.Insert method.
ListBox.Items.Insert(Index, Item)
-Listbox=name of control
-Index=specifies the position where Item is to be placed.
-Item=value to be added
Items.Remove/Items.Remove At Methods:
-Both methods remove one item from a list box Items property.
Listbox.Items.Remove(Item)
Listbox.Items.RemoveAt(Index)
Items.Clear Method:
-Erases all items in Items property.
ListBox.Items.Clear()
See pg. 295 for more properies of collections
5.3 Do While Loop
-Loops, or repetition structure, causes one or more statements to repeat.
-Do While loop has two important parts: 1)Boolean expression that is tested for True or False value, and 2) statement or group of statements that is repeated as long as the Boolean Expression is true.
Format:
Do While BooleanExpression
Statement
(More statements may follow)
Loop
-You must add something to a loop so it may stop. This is where Counters come into play as they regularly increment/decrement a variable each time a loop repeats. This gives it a chance of finally stopping, or else it'd be an infinite loop.
Example:
intCount=0
Do While intCount<10
lstOutput.Items.Add("Hello")
intCount +=1 <--------This adds "1" to intCount every time these statements are looped.
Loop
-Pretest Loop: The boolean expression is tested first. If it's true, the loop executes. Repeats until expression is false.
-Posttest Loop: The loop is executed first, and then the boolean expression is tested. If it's true, it repeats. If false, it stops.
Difference from Pretest/Posttest loops:
Dim intCount As Integer=100
Do While intCount<10
Messagebox.Show("Hello World")
intCount +=1
Loop This is a pre-test.
Dim intCount As Integer=100
Do
Messagebox.Show("Hello World")
intCount+=1
Loop While intCount<10 This is a post-test.
-You can use loops to keep a running total. variables used as accumulators are used.
5.4 Do Until/For Next loops
-Do Until loops are basically the opposite of the Do While loops. For Do Until, it'll keep looping as long as the boolean expression is false and stops when the expression is true.
Do Until Boolean Expression
Statement
Loop
-For Next loops is ideal for situations that require a counter. These initialize, test, and increment a counter variable.
For Countervariable=StartValue to EndValue Step (Increment)
Statement
Next (CounterVariable)
Example:
For intCount=1 to 10
MessageBox.Show("Hello")
Next
-The step value is the value add to the counter variable at the end of each loop in the For..Next loop.
5.5 Nested Loops
-A nested loop is a loop inside another loop. A clock is a good example of this, as each hand spins at a different rate.
Rules:
1) An inner loop goes through all iterations for each iteration an outer loop does.
2) Inner loops complete their loops before outer loops do.
3) To get total number of iterations of a nested loop, multiply the number of iterations of all the loops.
5.6 Multicolumn List Boxes, Checked List Boxes, and Combo Boxes
Multicolumn
-The listbox control itself has a MultiColumn property that can be set to true or false. Default is false. If you set it to true, it causes the list box to display its list in columns. You set the size of the columns, in pixels, with ColumnWidth property.
Checked
-Variation of the ListBox control.
-CheckOnClick property determines whether items become checked.
-When set to false, user clicks an item once to select it, then clicks again to check it.
-When set to true, the user clicks an item only once to both select/check.
-You can access selected items in checked list boxes the same as you would with a list box
CheckedListBox.GetItemChecked(Index)
Combo Boxes
-Similar to list boxes
-Both display list of items to user.
-Both have Items,Items.Count, SelectedIndex, SelectedItem, and Sorted properties.
-Both have Items.Add, Items.Clear, Items.Remove, and Items.RemoveAt methods.
-All of these properties and methods work the same with combo/list boxes.
Different styles such as: Drop-Down, Simple, Drop-Down List
List boxes vs. Combo boxes
-Use a drop-down or simple combo box when you want to provide the user a list of items to select from but don't want to limit the user's input to items on the list.
-Use a list box or a drop-down list combo box when you want to limit the user's selection to a list of items.
5.7 Random Numbers
-Computers aren't capable of generating truly random numbers.
-Computers rely on carefully crafted formulas to generate pseudo-random numbers.
-To create random numbers, create a special type of object known as a Random object in memory.
Example: Dim rand as New Random
The Next Method
-Once you created the Random object, call its Next method to get a random integer number.
Example: Dim intNum as Integer
Dim rand as New Random
intNum=rand.Next()
This will contain a random number in "intNum" when this code executes. This has a random range of 0-2.1 billion. You can specify an upper limit by putting for example "100" in the parantheses to limit it from 0-99. The random integer's range also doesn't have to start at zero.
Example: intNum=rand.Next(10)+1
This statement will first have a range of 0-9, but the +1 will make the range 1-10 instead.
The NextDouble Method
-This will get a random floating-point number between 0.0 and 1.0 (not including 1.0).
5.8 Simplifying Code with the With...End With Statement
-Instead of writing:
txtName.Clear ()
txtName.Forecolor=Color.Blue
txtName.BackColor=Color.Yellow
etc, you can use With...End With to simplify that using
With txtName
.Clear ()
.ForeColor=Color.Blue
.BackColor=Color.Yellow
etc.
5.9 ToolTips
-Small box displayed when the user holds the mouse cursor over a control. A short description is shown of the control.
-ToolTip Control allows you to create tooltips for other controls on the form.
-A simple/quick way to ask a user to enter data. An input box displays a message and allows the user to enter input into a text-box. The box also has Ok/Cancel buttons.
-Use the InputBox function:
InputBox(Prompt [, Title] [, Default] [, Xpos] [, Ypos])
-Title is a string that appears in the input box's title bar.
-Default is the string initially displayed in the text-box when it first displays.
-Xpos/Ypos determine where the input box will be displayed on the screen.
-Prompt is the text you designate to be in the input box as a label.
5.2 List Boxes
-Displays a list of items and also allows users to select the items in the list.
-When a list box contains more items than can be displayed, a scroll bar will appear in the list box.
Items Property:
-Entries in the list box are stored in the property named Items. You can store values in the Item Property using the String Collection Editor.
Items.Count Property:
-Use this to determine the number of items stored in the list box. When no items are in the Items property, the Items.Count property=0.
Item Indexing:
-The first item in a list box collection has the value of "0", like in a string. Always think of "n-1" to get the last index value, where "n" is the actual number of items in the collection.
-To access the items in code, use something like: lstEmployees.Items (0), where 0 is the first object stored.
-If you want to assign an value in a list box to a variable, remember to convert it to the appropriate format (Using the CInt for an integer, .ToString( ) for string, etc).
-Use try and catch statements to handle exceptions caused by out of range values.
SelectedIndex Property:
-When the user selects an item in a list box, the index of the item is stored in the SelectedIndex property.
-When no item is selected, the SelectedIndex=-1.
SelectedItem Property:
-SelectedIndex contains index of the currently selected item. SelectedItem contains the item itself.
-Example: List box "lstFruit" contains Apples, pears, bananas. If the user has selected pears, the following statement copies the string pairs to variable strSelectedFruit:
strSelectedFruit=lstFruit.SelectedItem.ToString()
Sorted Property:
-Use this to alphabetize the items in the Items property. This is set to False by default. Set it to True to alphabetize.
Items.Add Method:
-To store values in Item property in realtime, use Items.Add.
ListBox.Items.Add (Item)
-List box=name of control
-Item=value to be added to Items property
Items.Insert Method:
-Insert an item at a specific position using the Items.Insert method.
ListBox.Items.Insert(Index, Item)
-Listbox=name of control
-Index=specifies the position where Item is to be placed.
-Item=value to be added
Items.Remove/Items.Remove At Methods:
-Both methods remove one item from a list box Items property.
Listbox.Items.Remove(Item)
Listbox.Items.RemoveAt(Index)
Items.Clear Method:
-Erases all items in Items property.
ListBox.Items.Clear()
See pg. 295 for more properies of collections
5.3 Do While Loop
-Loops, or repetition structure, causes one or more statements to repeat.
-Do While loop has two important parts: 1)Boolean expression that is tested for True or False value, and 2) statement or group of statements that is repeated as long as the Boolean Expression is true.
Format:
Do While BooleanExpression
Statement
(More statements may follow)
Loop
-You must add something to a loop so it may stop. This is where Counters come into play as they regularly increment/decrement a variable each time a loop repeats. This gives it a chance of finally stopping, or else it'd be an infinite loop.
Example:
intCount=0
Do While intCount<10
lstOutput.Items.Add("Hello")
intCount +=1 <--------This adds "1" to intCount every time these statements are looped.
Loop
-Pretest Loop: The boolean expression is tested first. If it's true, the loop executes. Repeats until expression is false.
-Posttest Loop: The loop is executed first, and then the boolean expression is tested. If it's true, it repeats. If false, it stops.
Difference from Pretest/Posttest loops:
Dim intCount As Integer=100
Do While intCount<10
Messagebox.Show("Hello World")
intCount +=1
Loop This is a pre-test.
Dim intCount As Integer=100
Do
Messagebox.Show("Hello World")
intCount+=1
Loop While intCount<10 This is a post-test.
-You can use loops to keep a running total. variables used as accumulators are used.
5.4 Do Until/For Next loops
-Do Until loops are basically the opposite of the Do While loops. For Do Until, it'll keep looping as long as the boolean expression is false and stops when the expression is true.
Do Until Boolean Expression
Statement
Loop
-For Next loops is ideal for situations that require a counter. These initialize, test, and increment a counter variable.
For Countervariable=StartValue to EndValue Step (Increment)
Statement
Next (CounterVariable)
Example:
For intCount=1 to 10
MessageBox.Show("Hello")
Next
-The step value is the value add to the counter variable at the end of each loop in the For..Next loop.
5.5 Nested Loops
-A nested loop is a loop inside another loop. A clock is a good example of this, as each hand spins at a different rate.
Rules:
1) An inner loop goes through all iterations for each iteration an outer loop does.
2) Inner loops complete their loops before outer loops do.
3) To get total number of iterations of a nested loop, multiply the number of iterations of all the loops.
5.6 Multicolumn List Boxes, Checked List Boxes, and Combo Boxes
Multicolumn
-The listbox control itself has a MultiColumn property that can be set to true or false. Default is false. If you set it to true, it causes the list box to display its list in columns. You set the size of the columns, in pixels, with ColumnWidth property.
Checked
-Variation of the ListBox control.
-CheckOnClick property determines whether items become checked.
-When set to false, user clicks an item once to select it, then clicks again to check it.
-When set to true, the user clicks an item only once to both select/check.
-You can access selected items in checked list boxes the same as you would with a list box
CheckedListBox.GetItemChecked(Index)
Combo Boxes
-Similar to list boxes
-Both display list of items to user.
-Both have Items,Items.Count, SelectedIndex, SelectedItem, and Sorted properties.
-Both have Items.Add, Items.Clear, Items.Remove, and Items.RemoveAt methods.
-All of these properties and methods work the same with combo/list boxes.
Different styles such as: Drop-Down, Simple, Drop-Down List
List boxes vs. Combo boxes
-Use a drop-down or simple combo box when you want to provide the user a list of items to select from but don't want to limit the user's input to items on the list.
-Use a list box or a drop-down list combo box when you want to limit the user's selection to a list of items.
5.7 Random Numbers
-Computers aren't capable of generating truly random numbers.
-Computers rely on carefully crafted formulas to generate pseudo-random numbers.
-To create random numbers, create a special type of object known as a Random object in memory.
Example: Dim rand as New Random
The Next Method
-Once you created the Random object, call its Next method to get a random integer number.
Example: Dim intNum as Integer
Dim rand as New Random
intNum=rand.Next()
This will contain a random number in "intNum" when this code executes. This has a random range of 0-2.1 billion. You can specify an upper limit by putting for example "100" in the parantheses to limit it from 0-99. The random integer's range also doesn't have to start at zero.
Example: intNum=rand.Next(10)+1
This statement will first have a range of 0-9, but the +1 will make the range 1-10 instead.
The NextDouble Method
-This will get a random floating-point number between 0.0 and 1.0 (not including 1.0).
5.8 Simplifying Code with the With...End With Statement
-Instead of writing:
txtName.Clear ()
txtName.Forecolor=Color.Blue
txtName.BackColor=Color.Yellow
etc, you can use With...End With to simplify that using
With txtName
.Clear ()
.ForeColor=Color.Blue
.BackColor=Color.Yellow
etc.
5.9 ToolTips
-Small box displayed when the user holds the mouse cursor over a control. A short description is shown of the control.
-ToolTip Control allows you to create tooltips for other controls on the form.
Sunday, February 20, 2011
Chapter 4 Summary
4.1
Code is executed sequentially, so it's order is significant to how the program executes. Using a decision structure, programs can execute different exceptions within the code. Conditionally executed is an action when a program executes different results when a user-driven decision is made. (Example: the book uses the "wear a coat" action if the user says it is cold outside. If the user clicks "no" instead, the "wear a coat" action is skipped over. These actions are only performed under a certain condition. These are known as "If...Then" statements.
4.2 The If...Then Statement
If...Then: causes other statements to execute only when an expression is true.
Looks something like:
"If expression Then
statement
(more statements may follow)
End If".
Basically tells the program that if the initial expression is true, then the statements between the If...Then and the End If are executed. Otherwise, they are skipped if the expression is false. Boolean expression is the term for the initial expression, as they can either be true or false.
Relational Operator: determines whether a specific relationship exists between two values.
Example: X>Y means is x greater than y?
The "=" operator in this case determines whether the operand on the left is equal to operand on the right.
See the test score example on page 210 to see the If...Then statement in use.
You can use math operators alongside relational operators, such as
"If intX+intY>20 Then
lblMessage.Text="It is true!"
End If
Math operators are always performed before relational operators when they are in the same expression.
Relational operators can be used alongside function calls as well.
-Boolean variables can also be used as "flags", which signals when some condition exists in the program, either as "true" or "false".
4.3 If...Then...Else Statement
Looks like:
If condition Then
statement
more statements
Else
statement
End If
Like the original If...Then statement, a Boolean expression is still evaluated. The "else" statement tells the program what to execute if the Boolean expression turns out to be false instead of true.
example:
If dblTemperature<40 Then
lblMessage.Text="A little cold, isn't it?"
Else
lblMessage.Text="Nice weather we'r having!"
End If
4.4 If...Then...ElseIf Statement
Example: When we decide to wear a jacket, we might think in terms of:
-If it is very cold, wear a heavy coat
-Else, if it is chilly, wear a light jacket
-Else, if it is windy, wear a windbreaker
-Else, if it is hot, wear no jacket
That type of decision making is the equivalent "If...Then...ElseIf" statements. Looks like:
If condition Then
statement
ElseIf condition Then
statement
(as many "ElseIf statements can be put here)
Else
statement
End If
It's set-up like a chain, with the Else part of one statement being linked to the If part of another. All the "ElseIf" statements make up all the possibilities that need to be tried. See pg. 218 for the example.
4.5 Nested If Statements
Nested If Statement: is an If statement that appears inside another If statement.
Example: Loan Qualifier.
-The outermost "If" is testing the following the expression "If dblSalary>30,000 Then"
-If this is true, the nested if statement is executed, shown in bold.
If dblSalary>30000 Then
If intYearsOnJob>2
lblMessage.Text="The applicant qualifies."
Else
lblMessage.Text="The applicant does not qualify."
End If
Else
If intYearsOnJob>5 Then
lblMessage.Text="The applicant qualifies."
Else
lblMessage.Text="The applicant does not qualify."
End If
End If
-However, if expression dblSalary>30000 isn't true, the Else part of the outermost If statement causes the nested If statement to execute, shown in bold.
Else
If intYearsOnJob>5 Then
lblMessage.Text="The applicant qualifies."
Else
lblMessage.Text="The applicant does not qualify."
End If
End If
4.6 Logical Operators
Logical Operators: combine two or more Boolean expressions into a single expression.
Examples:
And: combines two expressions into one. Both must be true for the overall expression to be true.
-"AndAlso" can be used to achieve short-circuit evaluation (basically, if the first part of the "And" operator turns out to be false, Visual Studio can skip over the second part as the entire expression is false regardless).
Or: combines two expressions into one. One or both expressions must be true for the overall to be true.
-"OrElse" can be used to achieve short-circuit evaluation (in this case, if the first part is true, Visual Studio can now skip the second part as the entire expresssion is true regardless).
Xor: combines two into one. One expression (not both) must be true for the overall to be true. If both are true (or both flse), then overall is false.
Not: reverses the logical value of an expression: makes a true expression false and a false expression true.
Logical operators can be used to check numerical ranges. Example:
If intX>=20 And intX <=40 Then
lblMessage.Text="The value is in the acceptable range."
End If
The If statement would only be true if the value is greater than 20 and less than 40.
An Or statement would be:
If intX<20 Or intX>40 Then
lblMessage.Text= "The value is outside the acceptable range."
End If
This checks if th number is either less than 20 or greater than 40. If it is either one of those ranges, it's outside the acceptable range. Make sure to use the right operator, if you used And instead of Or, you'll get an error as no value exists that is both greater than 40 and less than 20.
You can use these statements together, such as:
If intX<0 and intY>100 Or intZ=50 Then
statement
End If
4.7 Comparing, Testing and Working with Strings
Example:
strName1="Mary"
strName2="Mark"
If strName1=strName2 Then
lblMessage.Text="The names are the same"
Else
lblMessage.Text="The names are NOT the same"
End If
The "=" operator tests whether the strings are equal. "<>" ">" "<" "<=" ">=" can also all be used to test strings. You can use the greater than/less than operators because computers don't store characters as "A, B, C", they are stored as a numeric value. Because A comes before B, the numeric code for A is less than B, and so on.
You can test for whether a user has entered text into a text box by comparing the the text property to the predefined constant "String.Empty".
You can use the ToUpper/ToLower methods to change the case of the string. Example:
strLittleWord="Hello"
strBigWord=strLittleWord.ToUpper( )
This will turn "Hello" into "HELLO", and vice versa if .ToLower( ) is used instead.
IsNumeric Function
-Tests if a string contains a numeric value, true if it does, false if it doesn't.
"IsNumeric(StringExpression)"
Length Property
-Returns the number of characters in a string. Example:
"Herman" will be stored as the number 6, because there are 6 characters.
Dim strName As String="Herman"
Dim intNumChars As Integer
inNumChars=strName.Length
Can also determie length of a control's text property, using ControlName.Text.Length.
Trimming Spaces
You can trim leading/trailing spaces from strings using the StringExpression.TrimStart( ), StringExpression.TrimEnd( ), or StringExpression.Trim( ) methods.
You can trim spaces on a control's text property by using txtName.Text.Trim( ).
SubString Method
-Can be used to return a string within the string.
StringExpression.Substring(Start)
StringExpression.Substring(Start,Length)
Start refers to the character position (first character is 0, and so on).
The second method will give you exactly what you enter (the starting position and how many characters), and the first one will start at the position you give it and return all the characters that start from that position to the end of the string.
IndexOf Method
-Also first character position is 0 and so on.
-This searches for a character/string within a string.
Example:
Dim strName As String="Angelina Adams"
Dim intPosition As Integer
intPosition=strName.IndexOf("e")
This will return the integer "3" as "e" is in the third character position (remember first is 0)
Example:
Dim strName As String="Angelina Adams"
Dim intPosition As Integer
intPosition=strName.IndexOf("A", 1)
This will give the integer "9", as the 1 is telling the method to start at the first character position ("n") and to search for a capital A (a lowercase a and a capital A are different, keep this in mind). The "A" in Adams is in the 9th character position.
Example:
Dim strName As String="Angelina Adams"
Dim intPosition As Integer
intPosition=strName.IndexOf("A", 1, 7)
This will return the position of "-1", meaning the character position was not found. The 1 tells it where to start from in the string ("n" again) and to only search 7 character positions after the 1st character position. "A" is not found, so it returns -1.
4.8 More About Message Boxes
Here are different forms of message boxes.
MessageBox.Show(Message)
-This displays a message.
MessageBox.Show(Message, Caption)
-This displays a message, and "Caption" refers to what you want the title bar to display.
MessageBox.Show(Message, Caption, Buttons)
-This diplays a message, "Caption" is the title bar, and now you can choose what buttons you want using one of these:
-MessageBoxButtons.AbortRetryIgnore
-MessageBoxButtons.OK
-MessageBoxButtons.OKCancel
-MessageBoxButtons.RetryCancel
-MessageBoxButtons.YesNo
-MessageBoxButtons.YesNoCancel
These are pretty self-explanatory.
MessageBox.Show(Message, Caption, Buttons, Icon)
-This displays your message, your title bar caption, whatever button you selected, and you can choose the Icon(either an asterisk/"i" for information will be before your message, or an "x" or a "!" in a triangle, or a question mark) using:
-MessageBoxIcon.Asterisk
-MessageBoxIcon.Error
-MessageBoxIcon.Exclamation
-MessageBoxIcon.Question
Check page 243 for more.
MessageBox.Show(Message, Caption, Buttons, Icon, DefaultButton)
-Displays your message, displays your title bar caption, displays the buttons, displays the icon, and now chooses what button is the default (i.e. what button is clicked if the user presses "enter")
-MessageBoxDefaultButton.Button1
-Selects the leftmost button.
-MessageBoxDefaultButton.Button2
-Selects second button from the left.
-MessageBoxDefaultButton.Button3
-Selects third button from the left.
Determining Which Button The User Clicked
Now that you have your message box, use If...Then...ElseIf statements to tell the program what to do in case of the button click. It's not an event handler for message boxes as Visual Studio returns specific values in case of a message box button click.
Example:
Dim intResult As Integer
intResult=MessageBox.Show("Do you wish to continue?", "Please Confirm", MessageBoxButtons.YesNo)
If intResult=Windows.Forms.DialogResult.Yes Then
'Perform some action here
ElseIF intResult=Windows.Forms.DialogResult.No Then
'Perform some action here
End If
See pg. 244 for more details.
4.9 Select Case Statement
Much like "If...Then...ElseIf" (this performs a series of tests and branches when one of the tests is true) statements, this tests the value of an expression only once and then uses that value to determine which set of statements to branch to.
Example:
Select Case CInt(txtInput.Text
Case 1
MessageBox.Show("Day 1 is Monday.")
Case 2
MessageBox.Show("Day 2 is Tuesday.")
Case 3
MessageBox.Show("Day 3 is Wednesday.")
Case 4
MessageBox.Show("Day 4 is Thursday.")
Case 5
MessageBox.Show("Day 5 is Friday.")
Case 6
MessageBox.Show("Day 6 is Saturday.")
Case 7
MessageBox.Show("Day 7 is Sunday.")
Case Else
MessageBox.Show("That value is invalid.")
Basically, this compares the integer of CInt(txtInput.Text) to whatever number case. If the integer is 3, it'll go through all the cases until it gets to case 3 and display the message box "Day 3 is Wednesday".
4.10 Input Validation
-The process of inspecting input values and determining whether they are valid.
-Now that we have If...Then statements, we can determine if a specific value can be converted to a specific data type before we try to convert it.
Methods:
-Integer.TryParse: Two arguments, string (argument 1) and integer variable (argument 2). Attempts to convert string to an integer. If successful, method returns true. If not, returns false.
-Double.TryParse: Tries to convert string to double. If successful, returns true. If not, returns false.
-Decimal.TryParse: ^
-Single.TryParse: ^
-Date.TryParse: ^
Etc.
4.11 Radion Buttons/Check Boxes
-All radio buttons inside a group box are members of the same group.
-All radio buttons on a form not inside a group box are members of the same group.
-Have a text property.
-Have a CheckedChanged event that is triggered when a user selects/deselects a radio button. Double-click on one to create the code.
Example:
If radChoice1.Checked=True Then
MessageBox.Show("You selected Choice 1")
ElseIf radChoice2.Checked=True Then
MessageBox.Show("You selected Choice 2")
ElseIf radChoice3.Checked=True Then
MessageBox.Show("You selected Choice 3")
End If
You can use code to select a radio button, using an assignment statement to set the desired radion button's Checked property to "True":
radChoice1.Checked=True.
Check Box
-Text property for caption
-When it has focus, can be checked or unchecked using the spacebar
-Can use code to select or deselect a check box.
-chkChoice4.Checked=True
-Have event handlers when checked/unchecked like radio buttons.
4.12 Building The Health Club Membership Fee Calculator Application
Look in the book, complete the example.
Code is executed sequentially, so it's order is significant to how the program executes. Using a decision structure, programs can execute different exceptions within the code. Conditionally executed is an action when a program executes different results when a user-driven decision is made. (Example: the book uses the "wear a coat" action if the user says it is cold outside. If the user clicks "no" instead, the "wear a coat" action is skipped over. These actions are only performed under a certain condition. These are known as "If...Then" statements.
4.2 The If...Then Statement
If...Then: causes other statements to execute only when an expression is true.
Looks something like:
"If expression Then
statement
(more statements may follow)
End If".
Basically tells the program that if the initial expression is true, then the statements between the If...Then and the End If are executed. Otherwise, they are skipped if the expression is false. Boolean expression is the term for the initial expression, as they can either be true or false.
Relational Operator: determines whether a specific relationship exists between two values.
Example: X>Y means is x greater than y?
The "=" operator in this case determines whether the operand on the left is equal to operand on the right.
See the test score example on page 210 to see the If...Then statement in use.
You can use math operators alongside relational operators, such as
"If intX+intY>20 Then
lblMessage.Text="It is true!"
End If
Math operators are always performed before relational operators when they are in the same expression.
Relational operators can be used alongside function calls as well.
-Boolean variables can also be used as "flags", which signals when some condition exists in the program, either as "true" or "false".
4.3 If...Then...Else Statement
Looks like:
If condition Then
statement
more statements
Else
statement
End If
Like the original If...Then statement, a Boolean expression is still evaluated. The "else" statement tells the program what to execute if the Boolean expression turns out to be false instead of true.
example:
If dblTemperature<40 Then
lblMessage.Text="A little cold, isn't it?"
Else
lblMessage.Text="Nice weather we'r having!"
End If
4.4 If...Then...ElseIf Statement
Example: When we decide to wear a jacket, we might think in terms of:
-If it is very cold, wear a heavy coat
-Else, if it is chilly, wear a light jacket
-Else, if it is windy, wear a windbreaker
-Else, if it is hot, wear no jacket
That type of decision making is the equivalent "If...Then...ElseIf" statements. Looks like:
If condition Then
statement
ElseIf condition Then
statement
(as many "ElseIf statements can be put here)
Else
statement
End If
It's set-up like a chain, with the Else part of one statement being linked to the If part of another. All the "ElseIf" statements make up all the possibilities that need to be tried. See pg. 218 for the example.
4.5 Nested If Statements
Nested If Statement: is an If statement that appears inside another If statement.
Example: Loan Qualifier.
-The outermost "If" is testing the following the expression "If dblSalary>30,000 Then"
-If this is true, the nested if statement is executed, shown in bold.
If dblSalary>30000 Then
If intYearsOnJob>2
lblMessage.Text="The applicant qualifies."
Else
lblMessage.Text="The applicant does not qualify."
End If
Else
If intYearsOnJob>5 Then
lblMessage.Text="The applicant qualifies."
Else
lblMessage.Text="The applicant does not qualify."
End If
End If
-However, if expression dblSalary>30000 isn't true, the Else part of the outermost If statement causes the nested If statement to execute, shown in bold.
Else
If intYearsOnJob>5 Then
lblMessage.Text="The applicant qualifies."
Else
lblMessage.Text="The applicant does not qualify."
End If
End If
4.6 Logical Operators
Logical Operators: combine two or more Boolean expressions into a single expression.
Examples:
And: combines two expressions into one. Both must be true for the overall expression to be true.
-"AndAlso" can be used to achieve short-circuit evaluation (basically, if the first part of the "And" operator turns out to be false, Visual Studio can skip over the second part as the entire expression is false regardless).
Or: combines two expressions into one. One or both expressions must be true for the overall to be true.
-"OrElse" can be used to achieve short-circuit evaluation (in this case, if the first part is true, Visual Studio can now skip the second part as the entire expresssion is true regardless).
Xor: combines two into one. One expression (not both) must be true for the overall to be true. If both are true (or both flse), then overall is false.
Not: reverses the logical value of an expression: makes a true expression false and a false expression true.
Logical operators can be used to check numerical ranges. Example:
If intX>=20 And intX <=40 Then
lblMessage.Text="The value is in the acceptable range."
End If
The If statement would only be true if the value is greater than 20 and less than 40.
An Or statement would be:
If intX<20 Or intX>40 Then
lblMessage.Text= "The value is outside the acceptable range."
End If
This checks if th number is either less than 20 or greater than 40. If it is either one of those ranges, it's outside the acceptable range. Make sure to use the right operator, if you used And instead of Or, you'll get an error as no value exists that is both greater than 40 and less than 20.
You can use these statements together, such as:
If intX<0 and intY>100 Or intZ=50 Then
statement
End If
4.7 Comparing, Testing and Working with Strings
Example:
strName1="Mary"
strName2="Mark"
If strName1=strName2 Then
lblMessage.Text="The names are the same"
Else
lblMessage.Text="The names are NOT the same"
End If
The "=" operator tests whether the strings are equal. "<>" ">" "<" "<=" ">=" can also all be used to test strings. You can use the greater than/less than operators because computers don't store characters as "A, B, C", they are stored as a numeric value. Because A comes before B, the numeric code for A is less than B, and so on.
You can test for whether a user has entered text into a text box by comparing the the text property to the predefined constant "String.Empty".
You can use the ToUpper/ToLower methods to change the case of the string. Example:
strLittleWord="Hello"
strBigWord=strLittleWord.ToUpper( )
This will turn "Hello" into "HELLO", and vice versa if .ToLower( ) is used instead.
IsNumeric Function
-Tests if a string contains a numeric value, true if it does, false if it doesn't.
"IsNumeric(StringExpression)"
Length Property
-Returns the number of characters in a string. Example:
"Herman" will be stored as the number 6, because there are 6 characters.
Dim strName As String="Herman"
Dim intNumChars As Integer
inNumChars=strName.Length
Can also determie length of a control's text property, using ControlName.Text.Length.
Trimming Spaces
You can trim leading/trailing spaces from strings using the StringExpression.TrimStart( ), StringExpression.TrimEnd( ), or StringExpression.Trim( ) methods.
You can trim spaces on a control's text property by using txtName.Text.Trim( ).
SubString Method
-Can be used to return a string within the string.
StringExpression.Substring(Start)
StringExpression.Substring(Start,Length)
Start refers to the character position (first character is 0, and so on).
The second method will give you exactly what you enter (the starting position and how many characters), and the first one will start at the position you give it and return all the characters that start from that position to the end of the string.
IndexOf Method
-Also first character position is 0 and so on.
-This searches for a character/string within a string.
Example:
Dim strName As String="Angelina Adams"
Dim intPosition As Integer
intPosition=strName.IndexOf("e")
This will return the integer "3" as "e" is in the third character position (remember first is 0)
Example:
Dim strName As String="Angelina Adams"
Dim intPosition As Integer
intPosition=strName.IndexOf("A", 1)
This will give the integer "9", as the 1 is telling the method to start at the first character position ("n") and to search for a capital A (a lowercase a and a capital A are different, keep this in mind). The "A" in Adams is in the 9th character position.
Example:
Dim strName As String="Angelina Adams"
Dim intPosition As Integer
intPosition=strName.IndexOf("A", 1, 7)
This will return the position of "-1", meaning the character position was not found. The 1 tells it where to start from in the string ("n" again) and to only search 7 character positions after the 1st character position. "A" is not found, so it returns -1.
4.8 More About Message Boxes
Here are different forms of message boxes.
MessageBox.Show(Message)
-This displays a message.
MessageBox.Show(Message, Caption)
-This displays a message, and "Caption" refers to what you want the title bar to display.
MessageBox.Show(Message, Caption, Buttons)
-This diplays a message, "Caption" is the title bar, and now you can choose what buttons you want using one of these:
-MessageBoxButtons.AbortRetryIgnore
-MessageBoxButtons.OK
-MessageBoxButtons.OKCancel
-MessageBoxButtons.RetryCancel
-MessageBoxButtons.YesNo
-MessageBoxButtons.YesNoCancel
These are pretty self-explanatory.
MessageBox.Show(Message, Caption, Buttons, Icon)
-This displays your message, your title bar caption, whatever button you selected, and you can choose the Icon(either an asterisk/"i" for information will be before your message, or an "x" or a "!" in a triangle, or a question mark) using:
-MessageBoxIcon.Asterisk
-MessageBoxIcon.Error
-MessageBoxIcon.Exclamation
-MessageBoxIcon.Question
Check page 243 for more.
MessageBox.Show(Message, Caption, Buttons, Icon, DefaultButton)
-Displays your message, displays your title bar caption, displays the buttons, displays the icon, and now chooses what button is the default (i.e. what button is clicked if the user presses "enter")
-MessageBoxDefaultButton.Button1
-Selects the leftmost button.
-MessageBoxDefaultButton.Button2
-Selects second button from the left.
-MessageBoxDefaultButton.Button3
-Selects third button from the left.
Determining Which Button The User Clicked
Now that you have your message box, use If...Then...ElseIf statements to tell the program what to do in case of the button click. It's not an event handler for message boxes as Visual Studio returns specific values in case of a message box button click.
Example:
Dim intResult As Integer
intResult=MessageBox.Show("Do you wish to continue?", "Please Confirm", MessageBoxButtons.YesNo)
If intResult=Windows.Forms.DialogResult.Yes Then
'Perform some action here
ElseIF intResult=Windows.Forms.DialogResult.No Then
'Perform some action here
End If
See pg. 244 for more details.
4.9 Select Case Statement
Much like "If...Then...ElseIf" (this performs a series of tests and branches when one of the tests is true) statements, this tests the value of an expression only once and then uses that value to determine which set of statements to branch to.
Example:
Select Case CInt(txtInput.Text
Case 1
MessageBox.Show("Day 1 is Monday.")
Case 2
MessageBox.Show("Day 2 is Tuesday.")
Case 3
MessageBox.Show("Day 3 is Wednesday.")
Case 4
MessageBox.Show("Day 4 is Thursday.")
Case 5
MessageBox.Show("Day 5 is Friday.")
Case 6
MessageBox.Show("Day 6 is Saturday.")
Case 7
MessageBox.Show("Day 7 is Sunday.")
Case Else
MessageBox.Show("That value is invalid.")
Basically, this compares the integer of CInt(txtInput.Text) to whatever number case. If the integer is 3, it'll go through all the cases until it gets to case 3 and display the message box "Day 3 is Wednesday".
4.10 Input Validation
-The process of inspecting input values and determining whether they are valid.
-Now that we have If...Then statements, we can determine if a specific value can be converted to a specific data type before we try to convert it.
Methods:
-Integer.TryParse: Two arguments, string (argument 1) and integer variable (argument 2). Attempts to convert string to an integer. If successful, method returns true. If not, returns false.
-Double.TryParse: Tries to convert string to double. If successful, returns true. If not, returns false.
-Decimal.TryParse: ^
-Single.TryParse: ^
-Date.TryParse: ^
Etc.
4.11 Radion Buttons/Check Boxes
-All radio buttons inside a group box are members of the same group.
-All radio buttons on a form not inside a group box are members of the same group.
-Have a text property.
-Have a CheckedChanged event that is triggered when a user selects/deselects a radio button. Double-click on one to create the code.
Example:
If radChoice1.Checked=True Then
MessageBox.Show("You selected Choice 1")
ElseIf radChoice2.Checked=True Then
MessageBox.Show("You selected Choice 2")
ElseIf radChoice3.Checked=True Then
MessageBox.Show("You selected Choice 3")
End If
You can use code to select a radio button, using an assignment statement to set the desired radion button's Checked property to "True":
radChoice1.Checked=True.
Check Box
-Text property for caption
-When it has focus, can be checked or unchecked using the spacebar
-Can use code to select or deselect a check box.
-chkChoice4.Checked=True
-Have event handlers when checked/unchecked like radio buttons.
4.12 Building The Health Club Membership Fee Calculator Application
Look in the book, complete the example.
Saturday, February 12, 2011
Chapter 3 Summary
3.1
Gathering Text Input
Text box-rectangular area on a form that accepts keyboard input.
You can access the Text property of a TextBox control just like you would access any other properties.
(ex. txtInput.text)
To clear a text box, we use the formula of "Object.Method", object being the name of the object and method being the name of the method being called. In this case, it would be TextBoxName.Clear( ). This clears any input in that specific textbox.
Another way of clearing a text box is using "String.Empty" to clear the contents. In this case, we'd use an operator in the code. TxtBoxName.Text=String.Empty
String Concatenation
String concatenation is a way of combining different elements of input by using an operator. The ampersand (&) operator is used to combine two different inputs.
Example: lblMessage.Text = Good Morning " & "Charlie". This would assign "Good Morning Charlie" to the text property of the lblMessage control. Make sure to include the proper spaces in the code, or else the text may end up reading "GoodMorning Charlie" or "GoodMorningCharlie".
Aligning Controls in Design Mode
This section talks about the various methods and tools used to properly align controls on a form. Whenever a control is aligned with another control, certain color guide lines appear.
Blue guide line: Controls are aligned vertically.
Lavender guide line: Controls are aligned horizontally.
Both lines can appear at the same time too. This takes a lot of the guesswork out of making sure everything is properly aligned in a visually appealing manner.
The Focus Method
Focuse: The control that is receiving user input. One control at any time always has the focus when a program is running.
To tell what control has the focus in realtime, look for several different signs. If a text-box has a blinking cursor, it has the focus. If a button has the focus, it'll have a thin dotted line around it.
To actively assign a control the focus (in the book tutorial, it showed how to make a text-box cursor flash again after all text-boxes had been cleared), we can call the focus method. To do this, we use "ControlName.Focus( )".
TabIndex
Just like on a webpage, pressing the tab button shifts the focus around to different controls. The order this goes in is known as the tab order. By default, the tab order is assigned in the order in which you created the controls. However, this might not always be the exact order you'd like (due to rearragning, deleting, adding new controls, etc). You can modify the tab order by using the TabIndex Property. Each control is assigned a number which indicates its order. By changing this, you can change the tab order. An easier way of changing each TabIndex Property (instead of individually changing all) can be found by clicking "View" on the menu bar, and then "Tab Order". This displays the form in tab order selection mode, where you can click on the specific order you'd prefer.
If you don't want a control to get the focus when cycling through the tab order, assign it's TabStop property to "false".
Assigning Keyboard Access Keys to Buttons
Access Key: Also known as "mnemonic", is a key pressed in combination with the alt key. You can assign an access key to a button through its Text property. Book Example: A text property is set to "exit" for a button. To assign the access key "Alt+X" to close the application, change "Exit" in the text property to "E&xit".
Accept Button: is a button that is automatically clicked when "Enter" is pressed.
Cancel Button: is a button that is automatically clicked when "Esc" is pressed.
3.2
Variables/Data Types
Variable: a storage location in computer memory that holds data while a program is running. It's basically name which you assign that represents a location in the computer's RAM. Example: "intLength=112" stores the value 112 in that variable.
Variable Declaration: is a statement that creates a variable in memory when a program executes.
The general form for this is "Dim VariableName As DataType" Book Example: Dim intLength As Integer.
-Dim tells VB that a variable is being declared.
-intLength is variable name.
-Integer indicates the data type. Integer is used to hold numbers. To declare multiple variables, use commas in-between each VariableName.
Variable Names: Rules: 1) First character must be letter or an underscore. 2) May use letters, numberic digits, and underscores after first character (no spaces,periods, or other punctuations). 3) Names cannot exceed 1023 character. 4) Names cannot be already established VB Keywords.
Type Prefix: Generally a good idea for future reference to start with a type prefix. We already do this when naming controls, i.e. a text-box we use "txt" before the name. See table 3-1 on page 124 for more details.
Assigning Values to Variables: Use the = operator to assign variable names to values. Example: inUnitsSold = 20.
Integer Data Types: Integers are whole numbers.
-Byte: holds a vaue ranging from 0-255
-Short: Value range of -32,768-+32,767
-Integer: Value range of -2,147,483,648-+2,147,483,647
-Long: Ridiculous value range.
More in-depth breakdown, see pages 126-131.
Default Values/Initialization
When a variable is assigned, it's given a default value. An integer variable is automatically assigned "0". To initalize it, you can specify a starting value using the dim statement, ex: Dim intUnitsSold As Integer = 12.
Local Variable: When a variable is declared inside of a procedure (such as an event handler) it is referred to as a local varaible. An error will occur if one procedure attempts to access a local variable of another procedure.
Scope: refers to the part of a program in which a variable may be accessed. Restates the local variable bundaries. Different scopes allow for variables to have the same names.
3.3
Performing Calculations
Binary Operator: works with two operands. Example: 5 + 10 adds the values of two numbers.
Different operating signs include subtraction (-), multiplication (*), floating-point division (/) integer division (\), and exponentiation (^).
Date/Time
To get the date/time of the computer, you can use the dim statement to bring up either date, time, or both.
"Dim dtmSystemDate=Now" brings up the current date and time of the system.
All of the other calculations would be tedious to write down, so read this section!
This is getting too long, so I'll just pick key topics from the other sections
Type Conversion: This occurs when assigning various things to variables. When a variable is assigned, VB tries to convert it to another data type. For example, assigning a real number (12.5) to "intCount", VB will convert it to an integer variable, rounding up to 13.
Option Strict: Only widening conversions are allowed, where no data is lost.
Function: special type of procedure where data is sent to the function as input. The function performs an operation on the data, then sends it back as output.
Exceptions: These are ways to recover from errors beyond a programmer's control (i.e. the user inputs wrong data). To "gracefully" recover from these, exception handlers are used.
A try-catch statement is the format used for exceptions. These are formatted as
Try
Statement
Statement
Catch
Statement
Statement
End Try
These execute in the order that they appear in. If a statement in the try block causes an exception, it'll jump to the catch clause and execute a statement from there.
In the book example, the user entered "four thousand" instead of a numerical value. This threw an exception for the try clause, and jumped to the catch clause, which saved the error.
I started writing this blog as I was reading through the chapter. I had no idea how long this chapter was, so about half-way through I realized it'd be pointless to cover every single thing. I'll make sure to just cover the major points in Chapter 4.
Gathering Text Input
Text box-rectangular area on a form that accepts keyboard input.
You can access the Text property of a TextBox control just like you would access any other properties.
(ex. txtInput.text)
To clear a text box, we use the formula of "Object.Method", object being the name of the object and method being the name of the method being called. In this case, it would be TextBoxName.Clear( ). This clears any input in that specific textbox.
Another way of clearing a text box is using "String.Empty" to clear the contents. In this case, we'd use an operator in the code. TxtBoxName.Text=String.Empty
String Concatenation
String concatenation is a way of combining different elements of input by using an operator. The ampersand (&) operator is used to combine two different inputs.
Example: lblMessage.Text = Good Morning " & "Charlie". This would assign "Good Morning Charlie" to the text property of the lblMessage control. Make sure to include the proper spaces in the code, or else the text may end up reading "GoodMorning Charlie" or "GoodMorningCharlie".
Aligning Controls in Design Mode
This section talks about the various methods and tools used to properly align controls on a form. Whenever a control is aligned with another control, certain color guide lines appear.
Blue guide line: Controls are aligned vertically.
Lavender guide line: Controls are aligned horizontally.
Both lines can appear at the same time too. This takes a lot of the guesswork out of making sure everything is properly aligned in a visually appealing manner.
The Focus Method
Focuse: The control that is receiving user input. One control at any time always has the focus when a program is running.
To tell what control has the focus in realtime, look for several different signs. If a text-box has a blinking cursor, it has the focus. If a button has the focus, it'll have a thin dotted line around it.
To actively assign a control the focus (in the book tutorial, it showed how to make a text-box cursor flash again after all text-boxes had been cleared), we can call the focus method. To do this, we use "ControlName.Focus( )".
TabIndex
Just like on a webpage, pressing the tab button shifts the focus around to different controls. The order this goes in is known as the tab order. By default, the tab order is assigned in the order in which you created the controls. However, this might not always be the exact order you'd like (due to rearragning, deleting, adding new controls, etc). You can modify the tab order by using the TabIndex Property. Each control is assigned a number which indicates its order. By changing this, you can change the tab order. An easier way of changing each TabIndex Property (instead of individually changing all) can be found by clicking "View" on the menu bar, and then "Tab Order". This displays the form in tab order selection mode, where you can click on the specific order you'd prefer.
If you don't want a control to get the focus when cycling through the tab order, assign it's TabStop property to "false".
Assigning Keyboard Access Keys to Buttons
Access Key: Also known as "mnemonic", is a key pressed in combination with the alt key. You can assign an access key to a button through its Text property. Book Example: A text property is set to "exit" for a button. To assign the access key "Alt+X" to close the application, change "Exit" in the text property to "E&xit".
Accept Button: is a button that is automatically clicked when "Enter" is pressed.
Cancel Button: is a button that is automatically clicked when "Esc" is pressed.
3.2
Variables/Data Types
Variable: a storage location in computer memory that holds data while a program is running. It's basically name which you assign that represents a location in the computer's RAM. Example: "intLength=112" stores the value 112 in that variable.
Variable Declaration: is a statement that creates a variable in memory when a program executes.
The general form for this is "Dim VariableName As DataType" Book Example: Dim intLength As Integer.
-Dim tells VB that a variable is being declared.
-intLength is variable name.
-Integer indicates the data type. Integer is used to hold numbers. To declare multiple variables, use commas in-between each VariableName.
Variable Names: Rules: 1) First character must be letter or an underscore. 2) May use letters, numberic digits, and underscores after first character (no spaces,periods, or other punctuations). 3) Names cannot exceed 1023 character. 4) Names cannot be already established VB Keywords.
Type Prefix: Generally a good idea for future reference to start with a type prefix. We already do this when naming controls, i.e. a text-box we use "txt" before the name. See table 3-1 on page 124 for more details.
Assigning Values to Variables: Use the = operator to assign variable names to values. Example: inUnitsSold = 20.
Integer Data Types: Integers are whole numbers.
-Byte: holds a vaue ranging from 0-255
-Short: Value range of -32,768-+32,767
-Integer: Value range of -2,147,483,648-+2,147,483,647
-Long: Ridiculous value range.
More in-depth breakdown, see pages 126-131.
Default Values/Initialization
When a variable is assigned, it's given a default value. An integer variable is automatically assigned "0". To initalize it, you can specify a starting value using the dim statement, ex: Dim intUnitsSold As Integer = 12.
Local Variable: When a variable is declared inside of a procedure (such as an event handler) it is referred to as a local varaible. An error will occur if one procedure attempts to access a local variable of another procedure.
Scope: refers to the part of a program in which a variable may be accessed. Restates the local variable bundaries. Different scopes allow for variables to have the same names.
3.3
Performing Calculations
Binary Operator: works with two operands. Example: 5 + 10 adds the values of two numbers.
Different operating signs include subtraction (-), multiplication (*), floating-point division (/) integer division (\), and exponentiation (^).
Date/Time
To get the date/time of the computer, you can use the dim statement to bring up either date, time, or both.
"Dim dtmSystemDate=Now" brings up the current date and time of the system.
All of the other calculations would be tedious to write down, so read this section!
This is getting too long, so I'll just pick key topics from the other sections
Type Conversion: This occurs when assigning various things to variables. When a variable is assigned, VB tries to convert it to another data type. For example, assigning a real number (12.5) to "intCount", VB will convert it to an integer variable, rounding up to 13.
Option Strict: Only widening conversions are allowed, where no data is lost.
Function: special type of procedure where data is sent to the function as input. The function performs an operation on the data, then sends it back as output.
Exceptions: These are ways to recover from errors beyond a programmer's control (i.e. the user inputs wrong data). To "gracefully" recover from these, exception handlers are used.
A try-catch statement is the format used for exceptions. These are formatted as
Try
Statement
Statement
Catch
Statement
Statement
End Try
These execute in the order that they appear in. If a statement in the try block causes an exception, it'll jump to the catch clause and execute a statement from there.
In the book example, the user entered "four thousand" instead of a numerical value. This threw an exception for the try clause, and jumped to the catch clause, which saved the error.
I started writing this blog as I was reading through the chapter. I had no idea how long this chapter was, so about half-way through I realized it'd be pointless to cover every single thing. I'll make sure to just cover the major points in Chapter 4.
Subscribe to:
Comments (Atom)