Wyo VB Lecture Notes - Objects, Methods, & Properties
Objective #1: Use forms appropriately.
- A form is a basic building block of a Visual Basic project. Eventually, you'll be creating projects that consist of many forms. You'll also learn how forms can be
reused to save programming time and to give more consistency to a large project.
- A form has number of useful properties including the Text property. The form's Text property appears in the blue title bar at the top of the form. The default value of a form's Text property is Form1. You should change that entry to something like the name of the project.
- The default Name property of a form is Form1. I do not recommend that you rename a form even though I do recommend that you immediately rename other objects such as labels and buttons.
- You can think of a form as having two basic parts, its interface and its code. The interface is what the user will see when he/she executes the program. The code
is the behind-the-scenes part of the form that contains the crucial logic and code that makes the form work that way the programmer intends it to work.
- A form and the objects on a form are measured in pixels. The size of the pixels on your monitor depend on your computer's screen resolution settings. Popular screen
resolution settings are 640 pixels by 480 pixels, 800 pixels by 600 pixels, or 1024 pixels by 724 pixels where the first number is the width of the screen and the second measurement is the height of
the screen. Larger numbers of pixels in the resolution means the screen looks sharper with more detail. For now in this course, it is not recommended that you resize a form to make it fill up more
of the computer screen.
- The Size property of a form is used to determine its size. Actually, it is the two subproperties, Height and Width,
of the Size property that determine the size of the form. The Location property of a form is used with its two subproperties, X and Y,
to determine the location of the upper-left corner of the form on the screen.
- The Load method of a form appears in the code window when you double-click anywhere on the interface of the form.
Any code typed into the form's Load method executes as soon as the form is loaded. The default form of a project loads as soon as the user executes a
project.
Objective #2: Identify and use objects.
- In English class, you learn about grammar and the rules for writing sentences and paragraphs. In computer programming, we refer to this as syntax. Syntax is the set of symbols and operators that are used in Visual Basic including the period symbol, the equals symbol, double
quotes, parentheses, etc. along with the rules that you must follow in order to use them correctly.
- Keywords are commands that are defined in Visual Basic. Examples of keywords are Public, Class, Private, Sub,
and End. These words do not represent objects, properties, or methods. Rather they are defined keywords. An error will occur of course if you mispell or overlook a
necessary keyword.
- Objects (also known as controls) are the things that make up a program. Examples of objects include forms, textboxes, buttons, labels and
MessageBoxes.
Objective #3: Know how to place objects such as textboxes, labels, and buttons on a form and give them proper names.
- Textboxes, labels, and buttons are three very useful kinds of objects to use in a VB program.
- There are several ways to place objects on a form.
- You can double-click a Toolbox icon in order to place that object on the form. You may have to drag objects around the form in order to be able to see newly created ones.
- You can drag a Toolbox icon onto a form to place an object there.
- You can single-click the Toolbox icon to select it and then click and drag on the form itself to place and size an object.
- You should always rename objects such as buttons and labels AS SOON AS you place them on a form by typing something descriptive and appropriate in the object's Name property. For example, the default name of a button is Button1. You must not double-click the button and begin to type code in its Click method before you have renamed the button with a proper name such as btnClick.
The Name property of an object should begin with a proper prefix. Label's should start with lbl, button's should start with btn, and textboxes should begin with txt.
After the prefix, you must use a descriptive name for the object. If the descriptive name consists of two or more words,
each word should begin with an uppercase letter so it is easier for other programmers to quickly read the name of the object. There should be no spaces or symbols in the name of an object. For example, if the purpose of a button is to clear some labels than a good name would be btnClear. If the purpose of a label is to display the directions to a game then a good name would be lblDirections or even lblGameDirections. Notice the use of an uppercase G and uppercase D. This method of naming variables is called Hungarian Notation.
Good names for a button would
be:
btnClick
btnComputePrice
btnStep1
Bad names for a button would be:
X because it doesn't explain the purpose of the variable
ClickMe because it doesn't have a prefix
btnclick because the c is not uppercase
btnClickme because the m is not uppercase
btncomputeprice because it is difficult to read when uppercase letters are not used
btn compute price because the name includes spaces
btn-compute-price because the name includes the hyphen symbol
btn_compute_price because the name includes the underscore symbol
btnShowMeThe$ because the name includes the $ symbol
- A partial list of object prefixes can be found at support.microsoft.com/default.aspx?scid=KB;en-us;q110264 even though it doesn't contain some objects such as buttons that were added to recent versions of VB. Another list is found at http://www.rwc.uc.edu/thomas/Intro_OOP_Text/Misc/VB_prefixes.html
Objective #4: Use Click events to make a program interact with the user when he/she clicks the mouse.
- Visual Basic makes it easy to create event-driven programs. An event-driven program is one which responds to users' actions such as mouse clicks and mouse
movement. Before the 1990's, programming languages were considered to be procedural. The programmer simply wrote lines of code that executed
with a sequential flow of control. Those programs were not as interactive
as modern Visual Basic event-driven ones. However, sometimes user interactivity is a hindrance to effective program execution.
- A useful object that is found in practically every VB project is a button. A button allows the user to interact with the VB project since it can be clicked by the
user.
- The Text property of a button is used to present the word or short phrase that the user will be able to read on
the button.
- When a user clicks a button a click event causes the button's Click method to execute. For example, the following method named btnExit_Click causes the program to end when the user clicks
this button:
Private Sub btnExit_Click()
Application.Exit()
End Sub
- For now, until we learn about menus, you should include an Exit button in the lower-right corner of every form.
- To have VB create an empty button Click method, you should double-click on a button. Then you can type statements in the body of the method. Those statements will execute when the user clicks the button.
- A form has a Click method as well that executes when the user clicks anywhere on the form. The following method
named Form1_Click causes a message box to appear but only when the form is clicked
Private Sub Form1_Click()
MessageBox.Show("Hi")
End Sub
- To type the MessageBox statement into the form's Click method, it is easiest to open the code window and change
the ClassName listbox at the top-left of the code window to "Form1 events" and then change the MethodName listbox at the top-right of the code window to "Click". VB will create
an empty Form1_Click method that you can fill in with statements.
- Textboxes and labels also have Click methods that can be created similarly.
Objective #5: Write assignment statements that assign values to properties.
- Each kind of object has its own set of properties. An object's properties affect the way it is displayed and the way that it interacts with the user and other
objects. Examples of properties include Name, Text, Font, BackColor, & ForeColor.
Referring to properties is tricky. You must first include the name of the object, followed by a dot operator ( . ), and then the name of the property.
In the statement
lblHello.Text = "Hello World"
Text is the name of a property. It is a property of the label named lblHello.
The value of the Text property is being set to the phrase "Hello World" in this statement. Setting the label's Text property to "Hello World" is called assignment. The whole statement is called an assignment statement. The equals symbol is called the assignment operator because the phrase "Hello World" is being "assigned to" the label lblHello . The phrase "Hello
World" is
called a string.
- In the statement,
lblStep1.Visible = True
lblStep1 is the name of a label object. Visible is an example of a property. The line of code causes the label to appear on the screen by setting its Visible property to True.
The statement
lblStep1.Visible = False
would make the label go invisible since it sets the Visible property to False.
- The statement
lblStep1.Text = "Design the interface"
causes the phrase "Design the interface" to be stored in the Text property of a label named lblStep1.
- The statement
txtMessage.Text = "Plan the code"
causes the phrase "Plan the code" to be stored in the Text property of a textbox named txtMessage.
- The statement
lblUser.Text = lblName.Text
causes whatever is stored in the Text property of lblName to also be displayed in the Text property of lblUser. In this case the assignment statement works from right to left with whatever is stored on the right of the equals symbol to be copied to the whatever is on the left of the equals symbol.
- The following statement clears a label named lblPhrase
lblPhrase.Text = ""
In the statement above, using two double quotes next to each other puts nothingness into the textbox. Two double quotes next to each other is called the empty string (also known as the null
string). Do not put a space between the double quotes since a space is not considered to be nothingness. When typing an online password typing extra spaces before or after the password could prevent you from logging in so spaces do count for something according to a computer.
- Do not confuse the Text property with the Name property of an object. The Text property usually Name property is used to refer to the object in the source code. Name properties can never have a space. Also, Name properties should begin with an appropriate prefix (e.g. lbl, btn, or txt).
- In the statement,
lblStep1.Visible = True
lblStep1 is the name of a label object. Visible is an example of a property. The line of code causes the label to appear on the screen by setting its Visible property to True.
The statement
lblStep1.Visible = False
would make the label go invisible since it sets the Visible property to False.
- The statement
lblOutput.Text = "My Name is Earl"
causes the phrase "My Name is Earl" to be stored in the Text property of a label named lblOutput.
- Notice that you normally find the object being named followed by the dot operator and then the property followed by an equals symbol and then the value that is being stored in the object's property as in
lblStep1.Visible = True
An error occur if you type it backwards like this
True = lblStep1.Visible
- Sample exercises in which you have to write an assignment statement
- Make a label named lblStep2 become invisible.
Answer: lblStep2.Visible = False
- Set a label named lblStep3's Text property to the phrase "Write the code"
Answer: lblStep3.Text = "Write the code"
- Make the phrase "Design the interface" appear in a label named lblStep1
Answer: lblStep1.Text = "Design the interface"
- Clear a label named lblStep1 so that nothing appears in its Text property.
Answer: lblStep1.Text = ""
- Clear a label named lblStep2 by setting its property to the empty string.
Answer: lblStep2.Text = ""
- Clear a label named lblStep3.
Answer: lblStep3.Text = ""
- Set lblMyName equal to whatever is currently displayed in lblYourName.
Answer: lblMyName.Text = lblYourName.Text
- Display whatever is currently found in lblYourName in a label named lblMyName.
Answer: lblMyName.Text = lblYourName.Text
Objective #6: Make use of the concatenation operator.
- The + symbol is sometimes used as an addition operator to add two numbers like it is in mathematics. In this example
lblAnswer.Text = 10 + 5
The number 15 will appear in the label named lblAnswer.
- However in other situations the + symbol is used as the concatenation operator. Concatenation occurs when you join two pieces of text (also known as strings) together as in
lblName.Text = "Wyomissing" + "Spartans"
in which case the text "WyomissingSpartans" will appear in the label named lblName.
If lblName.Text currently stores the name "Earl" then the statement
lblOutput.Text = "My Name is " + lblName.Text
causes the phrase "My Name is Earl" to be stored in lblOutput.
- However, if a number such as 5 is typed into lblNumber and the following statement executes
lblAnswer.Text = 10 + lblNumber.Text
the number 15 will appear in lblAnswer since the mathematical sum of 10 plus 5 is computed and stored in lblAnswer. In this case, VB treats the plus symbol as an addition operator since it knows that it is surrounded by two numbers rather than pieces of text.
- In this example
MessageBox.Show("My name is " + lblName.Text)
the phrase "My name is Earl" will appear in a message box if the word "Earl" is stored in lblName.
- In this example
lblOutput.Text = "Mr. " + txtName.Text
the phrase "Mr. Minich" will appear in the label named lblOutput if the textbox txtName stores the word "Minich".
- In this example
MessageBox.Show("Penn" + "sylvania")
the word "Pennsylvania" will appear in a message box.
- Study these sample exercises in which you have to write statements that use concatenation:
- Use the + concatenation operator to concatenate what is stored in lblSchool to the end of the phrase "My school is " and display the whole thing in a message box.
Answer: MessageBox.Show("My school is " + lblSchool.Text)
- Use the + concatenation operator to concatenate "Dr. " to the front of what is stored in a textbox named txtDoctor and display the whole thing in lblFullName.
Answer: lblFullName.Text = "Dr." + txtDoctor.Text
- Write a line of code that concatenates the words (also known as strings), "Philadelphia" and "Eagles", and stores the whole thing in a message box.
Answer: MessageBox.Show("Philadelphia" + "Eagles")
Objective #7: Identify and use methods.
- Methods are actions that a programmer can use with objects. Examples of methods include Load, Show, Click, Exit, & Clear.
In the statement
Application.Exit()
Exit is the name of a method. This statement can be used to end the program. Notice that methods are always followed
by a set of parentheses.
In the statement
MessageBox.Show("Hello World")
Show is a method.
- In the statement
txtUserInput.Clear()
Clear is the name of a method. It is a method that works with textbox objects. This statement causes the Text property
of a textbox named txtUserInput to be emptied.
- You should be able to write out a whole method. A method always begins with a line that starts with Private Sub.... and a method ends with the line of code End Sub. One or more statements are typed inside the body of a method. The body statements are indented for good style.
For example, if you are asked to write a method that displays "Hello Jupiter" in a message box when a button named btnClickHere is clicked, here is the answer you should give
Private Sub btnClickHere_Click()
MessageBox.Show("Hello Jupiter")
End Sub
In this class, you are not expected to write the complicated code that goes in the parentheses on the first line of the method. The name of the method is btnClickHere_Click however the name of the method includes the name of the object that is being clicked (btnClickHere) followed by an underscore ( _ ) which is followed by the event (i.e. user's interaction with the computer.)
- If you are asked to write a method that causes the program to end when a button named btnExit is clicked, your answer would be
Private Sub btnExit_Click()
Application.Exit()
End Sub
- If you are asked to write a method that causes a label named lblStep1 to disappear when a button named btnClear is clicked, your answer would be
Private Sub btnClear_Click()
lblStep1.Visible = False
End Sub
- If you are asked to write a method that causes the phrase "I attend Wyomissing Area High School" to appear in a label named lblOutput when a button named btnSchool is clicked, your answer would be
Private Sub btnSchool_Click()
lblOutput.Text = "I attend Wyomissing Area High School"
End Sub
- If you are asked to write a method that causes the phrase "Hello World" to show up in a message box as soon as the program is executed, your answer would be
Private Sub Form1_Load()
MessageBox.Show("Hello World")
End Sub
Notice that the event is Load since it automatically executes first when a program is started.
- If you are asked to write a method that displays the total cost of purchasing five items at $50 each in a label named lblTotalCost when the
user clicks a button named btnCompute, your answer would be
Private Sub btnCompute_Click()
lblTotalCost.Text = 5 * 50
End Sub
- If you are asked to write a method that displays the total cost of purchasing the number of items typed into a textbox named txtInput where items at priced at $50 each and to show that total cost in a label named lblTotalCost when the
user clicks a button named btnCompute, your answer would be
Private Sub btnCompute_Click()
lblTotalCost.Text = txtInput.Text * 50
End Sub
This assumes that the user types a number such as 5 into the textbox.