Visual Basic 1

70
Visual Basic 1 Basics

description

Visual Basic 1. Basics. Index of project examples in this ppt. My CSCI 110 powerpoints will have an index of the VB examples generally as the 2 nd slide. For this ppt show, here is an index of project examples The Two-textboxes example A Messagebox example The F to C converter - PowerPoint PPT Presentation

Transcript of Visual Basic 1

Page 1: Visual Basic 1

Visual Basic 1

Basics

Page 2: Visual Basic 1

Index of project examples in this ppt

My CSCI 110 powerpoints will have an index of the VB examples generally as the 2nd slide. For this ppt show, here is an index of project examples

• The Two-textboxes example• A Messagebox example• The F to C converter• Gaddis/Irvine text comments and chapter

1 screenshots

Page 3: Visual Basic 1

About the Schneider text examples

• VB 2005 Express edition can be downloaded free from MS to install on your own machine.

• You will need the 2005 edition VB to run the examples on the (other) text CD.

• However, my examples and the text examples should run in the labs, which have this edition of VB.

• As the semester progresses I will update our labs, projects and these powerpoints to reflect more examples from our text.

Page 4: Visual Basic 1

Here’s a VB form example: hourly wage calculations. We will write this program next week.

Page 5: Visual Basic 1

About VB

• VB is a (sort of) object-oriented language with a large IDE providing much developer support.

• Because of this, the environment is as hard to learn as the language, or harder!

• But it won’t be hard to develop impressive VB projects right away.

Page 6: Visual Basic 1

VB IDE

• IDE means integrated development environment.

• An IDE provides a means of developing and test-running software.

• The VB IDE is “part of” MS’s large .NET software system.

• There is quite a lot of mid-size enterprise sw development going on in VB!

Page 7: Visual Basic 1

VB version etc

• Labs should have the 2005 version of VB in the programming folder.

• This large program will take a while to load and VB programs will generally run fairly slowly from within the IDE.

• You can download free .NET software for your home computer from Microsoft.

Page 8: Visual Basic 1

To run VB: Click on the MS studio.net icon (probably in the programming folder)

Page 9: Visual Basic 1

Select windows application

Page 10: Visual Basic 1

Select new project (windows application), then select VB project from other types and click ok.

Page 11: Visual Basic 1

Note: You can give a project a special name by typing something else where it says name when you select New

Project. This is a good idea, because it will get hard to remember what’s what.

Page 12: Visual Basic 1

Creating a VB application in the express edition…view toolbox selected

Page 13: Visual Basic 1

A button with the hot key (alt-P) defined

Page 14: Visual Basic 1

Selecting new vb project (as per above) will open the form design interface

Page 15: Visual Basic 1

Selecting “View” on menu bar opens various window “view” options. Here, “view toolbox”

was selected.

Page 16: Visual Basic 1

Pull down the View options on the menubar

• Use the toolbox to select “tools” (called “controls” in VB) for your project

• Use the properties window(s) to set properties for your form and its control components.

• Use the solution explorer window to view the different elements of your solution.

Page 17: Visual Basic 1

Plopping components on your form

• Either double clicking a component in the toolbox menu, or clicking the component in the toolbox then clicking on your form, will put a control on your form.

• Once there, you can “select” it, resize it, align it, or drag it to where you want it to go, or add other properties to it like tab order or a tooltip.

Page 18: Visual Basic 1

Here’s a form with a couple of textboxes plopped on it

Page 19: Visual Basic 1

Some popular components• Textboxes, buttons, and labels are the most

popular components. Textboxes hold text - often user input.

• Labels are for labeling other components, usually.

• Buttons can be “pressed” to fire an event.• Picture boxes can “hold” images• comboboxes allow multiple choices.• Listboxes are like multi-line textboxes,

(Textboxes can also be set to be multiline).• Radiobuttons and checkboxes display available

choices: the user can select/deselect them

Page 20: Visual Basic 1

More on controls

• Controls can be grouped into groupboxes to help rationalize a complicated display.

• There are other types of controls as well – we won’t learn how to use them all this semester.

• You are already familiar with many controls as a user of window applications.

Page 21: Visual Basic 1

Running your VB application

• At any time during development, as long as you have no errors, you can “run” your application.

• To check for errors: Select build from the menubar and then select build solution (or rebuild)

• To run or check for errors: Select Debug on the menu bar, and then pick start or press F5.

Page 22: Visual Basic 1

Running an application with two textboxes (there’s no functionality)

Page 23: Visual Basic 1

Note

• You need to close your running application (window) before continuing development on it. Just click the X in the upper right corner of the running form’s window or, in the debug menu, select “stop debugging”.

• It is useful to “build” or “debug” periodically to make sure you have what you want and what you have works.

Page 24: Visual Basic 1

Selecting the form and editing the text property in the properties window allows you to change the text displayed on the form, its “name”, when the

form comes up

Page 25: Visual Basic 1

More “basic” development: Let’s add functionality to a form

• Clicking on the blank form in the development window will cause a “code window” to pop up. You can provide code specifying the action to be taken when the form is clicked.

Page 26: Visual Basic 1

Events

• VB, VC++ and Java are event-driven languages.

• This means mouse-clicks or letters typed at the keyboard may “fire” (start, initiate, cause) events.

• When events are fired, the programmer can specify what is supposed to happen.

Page 27: Visual Basic 1

Subroutines

• Subroutines are the Basic program language name for programmer-specified functionality.

• They are referred to as “sub” in the VB code.• VB helps you to write subs by providing stubs for any

event-fired subroutine.• This saves memorizing some things. It also saves typing

and time. • BUT: You must be careful: make sure the event sub

which is stubbed in is the one you want.• Cutting and pasting stubbed subs can be dangerous

since some stubbed values may still need editing.

Page 28: Visual Basic 1

Our first vb sub

• Let’s open a little message window when the user clicks anywhere on the form.

• In VB, messagebox is the name of the little message window component.

• Double-clicking on the form in development will switch us to a code window where a sub for this event-handler has been stubbed for us.

Page 29: Visual Basic 1

Form Click sub stub

• Below is the stub for form click. • Be careful, as VB may stub in a sub for form load.

• In any case, you can edit the stub to look like this:

Private Sub Form1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Click

End Sub

Page 30: Visual Basic 1

Our sub

Private Sub Form1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Click

MessageBox.Show("A message!", "first VB example", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

‘comment…bold text is what you type End Sub

Page 31: Visual Basic 1

Remarks about this sub

• Fit code on one line or use the space-then-underscore to continue a VB statement onto the next line.

• Important note: Most of these slides show code spilling onto multiple lines, which won’t work.

• What you should type into the stubbed sub on one line is:

MessageBox.Show("A message!", "first VB example", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

Page 32: Visual Basic 1

More remarks on this subroutine

Private Sub Form1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Click

• Notice the name: Form1_Click. This is generated automatically, and would have specified a different name for the method if we had given our form a different name.

• In general, ComponentName_Click is the name of the subroutine handling mouseclicks on a control component named ComponentName.

• MyBase.Click is the event for clicking on the form.• We’ll learn more about the parenthetical arguments and

the “Handles…” another time.

Page 33: Visual Basic 1

Now, run the example (remember: select debug, then click start)

An empty form appears, but…click on it

Page 34: Visual Basic 1

A message box pops up

Page 35: Visual Basic 1

An exercise to test your understanding:

Fix your message box to look like this

Page 36: Visual Basic 1

Setting properties for components

• Clicking a component on your form will open its properties window (probably on the right.)

• You can also open properties window by selecting view>properties

• You can specify names and initial (text) values of control components.

• You can resize labels (or textboxes) or change the text font, for example, if the text doesn’t fit.

• You can align text in a component.• You can set colors.

Page 37: Visual Basic 1

Now let’s change the form• Add a label: Set its text property to Enter fahrenheit.

Give it a name like lblInput as its name property.• Add a textbox: set text property to blank contents, name

property to something like txtInput• Add another textbox: set read-only property to true (see

below) and name it, for example, txtOutput

Page 38: Visual Basic 1

VB Naming conventions• Although you can name components almost

anything you like, VB conventions recommend standard prefixes frm, lbl, btn, txt (and so on) for form, label, button, textbox (and so on).

• I gave my label and textboxes the names: lblPrompt, txtInput, txtOutput.

• Using standardized conventional names will help you remember what things are and what they are used for as your applications become more complicated.

Page 39: Visual Basic 1

VB component properties

• I put text in my label instructing the user what to do.

• I set input’s text to blank.• I set output to be read-only (not editable).• ‘&’ in the text property of a button defines a

hotkey for keyboard input. So, if the text on a button is “X&YZ” then typing the letter ‘Y’ on the keyboard is the same as clicking that button with the mouse.

• See the next slides for setting properties.

Page 40: Visual Basic 1

Setting properties• As you add components, clicking them will open the

properties window.• In the properties window, you can give the components

names, and set other property values.

Page 41: Visual Basic 1

Setting properties

• Clicking “elsewhere” on your form or in another window confirms property settings.

• Of course, you can change properties anytime.

• Remember to save your application each time you make changes.

Page 42: Visual Basic 1

Let’s look at the form (start debugger). Except for the message box there’s still no real functionality

Page 43: Visual Basic 1

What else do we want?

1. Get rid of the pop-up message box? Your choice.2. Make the form “go away” when we are done. (This is

already provided by Microsoft windows application code when the X is clicked in the upper right of the running application window.)

3. Add functionality: the famous F to C conversion from ninth grade. Recall the formula C=5.0/9.0*(F-32) . The parentheses and decimal points are needed.

4. Add a label for the answer5. Add two buttons. Give them names. (VB convention

would be to name them btnCompute and btnQuit)

Page 44: Visual Basic 1

Exercise to test your understanding: add some

components & set properties• Complete Lab 1 and Lab 2 for this week

Page 45: Visual Basic 1

My new form: still no functionality

Page 46: Visual Basic 1

event-driven programming, continued• VB makes handling events fairly easy, although

it is still pretty technical.• As previously mentioned, double-clicking a

control component in the form-development window brings up a code window with an empty subroutine already stubbed in.

• You provide the specific code you want for your application.

• It is still up to you to make sure this is what you really want!

Page 47: Visual Basic 1

More on the Visual environment

• VB and VC++ provide a lot of programmer support, prompting you with components, the proper code to provide, and the place your code should go.

• When prompted (with a pop-up window) you may ignore the suggestions and keep typing, or make a selection and hit the enter key to save some typing.

Page 48: Visual Basic 1

Back to the form

• How do we add functionality?• In design-mode, double-clicking a

component will open a code window where you can add the code you want for this “event”.

• You can also open the code window from the VIEW menu.

• Let’s add functionality to the compute button.

Page 49: Visual Basic 1

What’s involved?

1. We need to create appropriate variables to hold necessary values.

2. We need to compute whatever information we need.

3. We need to display the result so the user can see it.

Page 50: Visual Basic 1

The IPO model

• I-P-O = input-process-output• Many programs in real life and in this

class will follow the IPO model.• The user provides input, the program

processes it somehow, and then generates output.

• IPO is NOT the only model, transactions (at an ATM for example), are not simple IPO.

Page 51: Visual Basic 1

Declarations and variable types

• Declaring variables is REQUIRED in almost all programming languages.

• VB declarations must start with the reserved symbol Dim• VB supports MANY datatypes. Decimal, single, and

double are some of the “real” datatypes.• Textboxes and labels hold Strings. Strings contain

characters, possibly numeric in value, and are written with quotes, as in “Hello” and “1234”

• Although, when you type into a textbox you don’t put the quotes, you’ll need quotes on string constants in your project’s code to distinguish them from names.

Page 52: Visual Basic 1

Here’s some of the code

• We’ll need variables to hold the fahrenheit and celsius amounts. We’ll use Dim and make them Double. (Decimal or Single data types would also work).

• The code below functions, although it contains a potential problem which, as it happens, VB handles for us in this case.

• What’s the problem in the 2nd line?

Dim celsius, fahr As Double fahr = txtInput.Text ‘fahr should be a double…is it? celsius = (5.0 / 9.0) * (fahr - 32)

Page 53: Visual Basic 1

Comments

• An apostrophe begins a comment to the end of the line

• Although it may seem silly, you should put in comment blocks at the start of subs detailing the variables used, the input and output variables and parameters.

• You should comment complicated lines of code, because you may not remember in a week (or a year) why you did something a certain way.

Page 54: Visual Basic 1

An aside: Option Strict

• Setting Option Strict On (put Option Strict On before the first line of code in your code window) makes VB function more like C++ and Java – that is, it won’t do automatic conversions from a wider data type (say, String) to a narrower one (say Double or Integer).

• This is good programming practice and will help you avoid datatype mistakes.

• You can also set option strict on in the designer.• When option strict is not on, VB will convert

datatypes to match expression and assignments if it can.

Page 55: Visual Basic 1

An improvement

• Although VB will properly convert a string to a number (if the string contains a number and option strict is off) that’s not a good way to program, especially since it doesn’t give us the flexibility of handling the exception (that is, erroneous input & conversion thereof) ourselves.

• Parse is the name of the VB function to convert strings into numeric values. Integers and decimals can be parsed. We should write

fahr = Double.parse(txtinput.Text)• There are two steps being performed here: First get the

string from input, then convert it to a real number.

Page 56: Visual Basic 1

A complete (improved) subroutine

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click

Dim celsius, fahr As Double ‘my variables fahr = Decimal.parse(txtinput.Text) ‘get user input as a real celsius = (5.0 / 9.0) * (fahr - 32) ‘do arithmetic output.Text = celsius.ToString("N") ‘display answer End Sub

Page 57: Visual Basic 1

By the way…

• Classes Integer and Double both have parse methods to change a String into a numeric value. You should always use a method to do your conversions to numbers (or back to String)

Dim snum as String =“123.45”Dim inum as String=“6789”Dim dub as DoubleDim intval as Integerdub=Double.parse(snum) ‘gives the double 123.45intval=Integer.parse(inum) ‘gives the int 6789You can also use VB’s CStr or CDbl to convert to string (from a

numeric type) or to double (from string).Dub=CDbl(snum)Snum=CStr(intval)

Page 58: Visual Basic 1

Important note

• You won’t be able to blindly copy my code into your subroutines.

• For example, you’ll need to use YOUR component and data variable names.

• Remember about continuing statements to another line: You must use space-underscore or try to fit it onto one line.

Page 59: Visual Basic 1

The current form, running

Page 60: Visual Basic 1

Format specifiers for conversions of numbers to strings

• VB provides format specifications:• “N” or “n” for number, 2 decimal places given unless you

specify otherwise.• “P” or “p” for percentage. You may optionally specify

additional decimal places.• “D” or “d” for Integer only. You may optionally specify

places.• “C” or “c” for currency (dollar sign and 2 decimal places)• Value.toString(“N0”) converts value to a string with 0

decimal places.• Value.toString(“P3”) converts value to a string

“percentage” with three decimal places, as in “%5.678”

Page 61: Visual Basic 1

VB formats

• VB also provides date formatting which (probably) we’ll discuss another time.

Page 62: Visual Basic 1

Now, make the form go away

• Double click your “quit” button to bring up the code window.

• Here’s my function:

Private Sub btnquit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnquit.Click

Me.Close()

End Sub

Page 63: Visual Basic 1

Me.close()

• Me is always the name of your form, while it is running. You can refer to components as Me.componentName, as in, Me.txtinput and so on.

• Me.close() technnically just closes the window associated with the form.

Page 64: Visual Basic 1

Exercise: Add More functionality

• Add a clear button which clears out all the fields when pressed

• You might name it btnClear, put its text to “&clear” and add the btnClear_clicked subroutine to the code section:

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click

txtinput.Clear()

txtoutput.Clear()

End Sub

Page 65: Visual Basic 1

Running VB apps

• You can test and run your VB from the IDE using the debugger.

• Once completed, you can use your application like any other program, too.

• First, you’ll have to find the .exe file associated with your application.

• It is in the …/obj/debug directory.

Page 66: Visual Basic 1

In the …/obj/debug directory find the exe file

Page 67: Visual Basic 1

Click the exe to run an app

Page 68: Visual Basic 1

Is there any more to say?

• There are lots of ways to code this F to C example.

• You can probably think of many things we could do differently.

• Exercise 1: Build an application for computing gross pay for a single employee. Provide textboxes for payrate and hours worked, appropriate labels, and display gross pay.

Page 69: Visual Basic 1

Week 1 checklist: What should you be able to do? Easy list

• Find the VB icon, launch VB and edit/create a VB application.

• Give your application a different name than the default.• Run (in the debugger) your application at any time during

development.• View the toolbox.• Add a control (or two) to your form.• View the properties.• Edit properties for your control like TEXT and NAME.• Use VB conventions for naming controls.• Open the code view.

Page 70: Visual Basic 1

Week 1 checklist: you should be able to…

• Perform some simple arithmetic on values entered and display the result.

• Recognize datatypes and declare your variables appropriately in the proper location of the code view.