Jumat, 19 Juni 2009

Belajar vb.net volume 1#

Learn Visual Basic .NET


1. Introduction to the Visual Basic .NET Environment


Preview

• In this first class, we will do an overview of how to build a Windows application using Visual Basic .NET. You’ll learn a new vocabulary, a new approach to programming, and ways to move around in the Visual Basic .NET environment. Once finished, you will have written your first Visual Basic .NET program.



Course Objectives

• Understand the benefits of using Microsoft Visual Basic .NET as an application tool
• Understand Visual Basic .NET event-driven programming concepts, object-oriented programming terminology, and available controls
• Learn the fundamentals of designing, implementing, and distributing a Visual Basic .NET Windows application
• Learn to use the Visual Basic .NET toolbox
• Learn to modify object properties and use of object methods
• Use menu and toolbar design tools
• Learn how to read and write sequential files
• Understand proper debugging and error-handling procedures
• Gain an understanding of graphic methods and simple animations
• Obtain an introduction to the Windows Application Programming Interface (API) for multimedia effects
• Learn how to print text and graphics from a Visual Basic .NET application
• Gain skills to develop and implement an HTML-based help system
• Obtain an introduction to implementing Visual Basic .NET applications on the internet using the Web form



What is Visual Basic .NET?

• Visual Basic .NET is part of a grand new initiative by Microsoft. It is a complete re-engineering of Visual Basic for the Microsoft .NET framework. With Visual Basic .NET, you are able to quickly build Windows-based applications (the emphasis in this course), web-based applications and, eventually, software for other devices, such as palm computers.

• Windows applications built using Visual Basic .NET feature a Graphical User Interface (GUI). Users interact with a set of visual tools (buttons, text boxes, tool bars, menu items) to make an application do its required tasks. The applications have a familiar appearance to the user. As you develop as a Visual Basic .NET programmer, you will begin to look at Windows applications in a different light. You will recognize and understand how various elements of Word, Excel, Access and other applications work. You will develop a new vocabulary to describe the elements of Windows applications.

• Visual Basic .NET Windows applications are event-driven, meaning nothing happens until an application is called upon to respond to some event (button pressing, menu selection, ...). Visual Basic .NET is governed by an event processor. As mentioned, nothing happens until an event is detected. Once an event is detected, a corresponding event procedure is located and the instructions provided by that procedure are executed. Those instructions are the actual code written by the programmer. In Visual Basic .NET, that code is written using a version of the BASIC programming language. Once an event procedure is completed, program control is then returned to the event processor.




Event
Procedures

All Windows applications are event-driven. For example, nothing happens in Word until you click on a button, select a menu option, or type some text. Each of these actions is an event.

• The event-driven nature of applications developed with Visual Basic .NET makes it very easy to work with. As you develop a Visual Basic .NET application, event procedures can be built and tested individually, saving development time. And, often event procedures are similar in their coding, allowing re-use (and lots of copy and paste).


• Some Features of Visual Basic .NET

• All new, easy-to-use, powerful Integrated Development Environment (IDE)
• Full set of controls - you 'draw' the application
• Response to mouse and keyboard actions
• Clipboard and printer access
• Full array of mathematical, string handling, and graphics functions
• Can easily work with arrays of variables and objects
• Sequential file support
• Useful debugger and structured error-handling facilities
• Easy-to-use graphic tools
• Powerful database access tools (not covered in this course)
• Ability to develop both Windows and internet applications using similar techniques
• New common language runtime module makes distribution of applications a simple task

Visual Basic .NET versus Visual Basic

• Let’s get something straight right now – Visual Basic .NET is not a new version of Visual Basic. Visual Basic .NET is an entirely new product. If you are familiar with Visual Basic, Visual Basic .NET will look familiar, but there are many differences. And, for the most part, the differences are vast improvements over Visual Basic. When you realize that the BASIC language has not undergone substantial changes in 20 years, you should agree it was time for a clean-up and improvement.

• A few of the features of Visual Basic .NET, compared to Visual Basic:

• New Integrated Development Environment
• Uses Object-Oriented Programming (OOP) methods
• New controls and control properties
• Redesigned code window
• Zero-based arrays (no adjustable first dimension)
• Easier to use common dialog boxes
• Structured error-handling (no more On Error Go To)
• New menu design tools
• New techniques for working with sequential files
• All new graphics methods
• New approaches to printing from an application
• Improved support to incorporating help systems in applications
• New web forms for internet applications
• ADO.NET for database access (not covered in this course)

• To use Visual Basic .NET, you (and your users) must be using Windows 2000, Windows XP, or Windows NT. As of now, Visual Basic .NET applications will not run on Windows 9X or Windows Me machines.

• The Appendix to these notes is a useful reference for experienced Visual Basic programmers. In the Appendix, we provide a synopsis on how the material presented in this course for Visual Basic .NET differs from similar material for Visual Basic. The material is organized according to the 10 chapters (classes) provided in these notes. Also provided in the Appendix is a discussion on migrating existing Visual Basic applications to Visual Basic .NET.



A Brief Look at Object-Oriented Programming (OOP)

• Since Visual Basic was first introduced in the early 1990’s, a major criticism from many programmers (especially those using C and C++) was that it was not a true object-oriented language. And, with that limitation, many dismissed Visual Basic as a “toy” language. That limitation no longer exists!

• Visual Basic .NET is fully object-oriented. For this particular course, we don’t have to worry much about just what that means (many sizeable tomes have been written about OOP). What we need to know is that each application we write will be made up of objects. Just what is an object? It can be many things: a variable, a font, a graphics region, a rectangle, a printed document. The key thing to remember is that these objects represent reusable entities that are used to develop an application. This ‘reusability’ makes our job much easier as a programmer.

• In Visual Basic .NET, there are three terms we need to be familiar with in working with object-oriented programming: Namespace, Class and Object. Objects are what are used to build our application. We will learn about many objects throughout this course. Objects are derived from classes. Think of classes as general descriptions of objects, which are then specific implementations of a class. For example, a class could be a general description of a car, where an object from that class would be a specific car, say a red 1965 Ford Mustang convertible (a nice object!). Lastly, a namespace is a grouping of different classes used in the .NET world. One namespace might have graphics classes, while another would have math functions. We will see several namespaces in our work.

• For this course, if you remember namespace, class and object, you have sufficient OOP knowledge to build applications. The primary use for these terms is when searching for help on a particular topic. When seeking help, you need to know that an object comes from a class which comes from a namespace Once you complete this course, you can further delve into the world of OOP. Then, you’ll be able to throw around terms like inheritance, polymorphism, overloading, encapsulation, and overriding.

• The biggest advantage of the object-oriented nature of Visual Basic .NET is that it is no longer a “toy” language. In fact, Visual Basic .NET uses the same platform for development and deployment (incorporating the new Common Language Runtime (CLR) module) as the more esoteric languages (Visual C++ and the new Visual C#). Because of this, there should be no performance differences between applications written in Visual Basic .NET, Visual C++ .NET, or Visual C# .NET!

Structure of a Visual Basic .NET Windows Application

• We want to get started building our first Visual Basic .NET Windows application. But, first we need to define some of the terminology we will be using. In Visual Basic .NET, a Windows application is defined as a solution. A solution is made up of one or more projects. Projects are groups of forms and code that make up some application. In most of our work in this course, our applications (solutions) will be made up of a single project. Because of this, we will usually use the terms application, solution and project synonymously.

• As mentioned, a project (application) is made up of forms and code. Pictorially, this is:

Project












Application (Project) is made up of:

 Forms - Windows that you create for user interface
 Controls - Graphical features drawn on forms to allow user interaction (text boxes, labels, scroll bars, buttons, etc.) (Forms and Controls are objects.)
 Properties - Every characteristic of a form or control is specified by a property. Example properties include names, captions, size, color, position, and contents. Visual Basic .NET applies default properties. You can change properties when designing the application or even when an application is executing.
 Methods - Built-in procedures that can be invoked to impart some action to a particular object.
 Event Procedures - Code related to some object or control. This is the code that is executed when a certain event occurs. In our applications, this code will be written in the BASIC language (covered in detail in Chapter 2 of these notes).

 General Procedures - Code not related to objects. This code must be invoked or called in the application.
 Modules - Collection of general procedures, variable declarations, and constant definitions used by an application.

• The application displayed above has three forms and a single module. Visual Basic .NET uses a very specific directory structure for saving all of the components for a particular application. When you start a new project (solution), you will be asked for a Name and Location (directory). A folder named Name will be established in the selected Location. That folder will be used to store all solution files, project files, form and module files (vb extension) and other files needed by the project. Two subfolders will be established within the Name folder: Bin and Obj. The Obj folder contains files used for debugging your application as it is being developed. The Bin folder contains your compiled application (the actual executable code or exe file). Later, you will see that this folder is considered the ‘application path’ when ancillary data, graphics and sound files are needed by an application.

• In a project folder, you will see these files (and possibly more):

AssemblyInfo.vb Information on how things fit together
SolutionName.sln Solution file for solution named SolutionName
ProjectName.vbproj Project file – one for each project in solution
ProjectName.vbproj.user Another Project file – one for each project in solution
FormName.resx Form resources file – one for each form
FormName.vb Form code file – one for each form



Steps in Developing a Windows Application

 The Visual Basic .NET Integrated Development Environment (IDE) makes building an application a straightforward process. There are three primary steps involved in building a Visual Basic .NET application:

1. Draw the user interface by placing controls on a Windows form
2. Assign properties to controls
3. Write code for control events (and perhaps write other procedures)

These same steps are followed whether you are building a very simple application or one involving many controls and many lines of code.

 The event-driven nature of Visual Basic .NET applications allows you to build your application in stages and test it at each stage. You can build one procedure, or part of a procedure, at a time and try it until it works as desired. This minimizes errors and gives you, the programmer, confidence as your application takes shape.

 As you progress in your programming skills, always remember to take this sequential approach to building a Visual Basic .NET application. Build a little, test a little, modify a little and test again. You’ll quickly have a completed application. This ability to quickly build something and try it makes working with Visual Basic .NET fun – not a quality found in some programming environments! Now, we’ll start Visual Basic .NET and look at each step in the application development process.



Starting Visual Basic .NET

• We assume you have Visual Basic .NET installed and operational on your computer. In these notes, we use a version of Visual Basic .NET included as a part of Microsoft Visual Studio .NET. Visual Studio .NET includes not only Visual Basic .NET, but also Visual C++ .NET and Visual C# .NET. All three languages use the same Integrated Development Environment (IDE). If you are using the stand-alone Visual Basic .NET product, some of the instructions and screens shown for starting a project may differ slightly.

• To start Visual Basic .NET:

 Click on the Start button on the Windows task bar.
 Select Programs, then Microsoft Visual Basic .NET
 Click on Visual Basic .NET

(Some of the headings given here may differ slightly on your computer, but you should have no trouble finding the correct ones.)

• Visual Basic .NET will start and (among other things) a screen will appear asking if you to choose between Open Project or New Project. Of course, later after completing some projects, you might choose to open an existing project. For now, click New Project and the following dialog box should appear:



• Recall this screen is from Visual Studio, so we have selected Visual Basic Projects under Project Type. We want to build a Windows Application, so make that choice under Templates.

• Choose a directory Location for your project (the Browse button is available for changing the listed directory) and assign a Name. Recall these are the folders all appropriate project files will be stored in. Once done, click OK and the Visual Basic .NET development environment will appear. Your project will consist of a single Windows form.



Visual Basic .NET Integrated Development Environment (IDE)

• The Visual Basic .NET IDE is where we build and test our application via implementation of the three steps of application development (draw controls, assign properties, write code). As you progress through this course, you will learn how easy-to-use and helpful the IDE is. There are many features in the IDE and many ways to use these features. Here, we will introduce the IDE and some of its features. You must realize, however, that its true utility will become apparent as you use it yourself to build your own applications.

• Several windows appear when you start Visual Basic .NET. Each window can be viewed (made visible or active) by selecting menu options, depressing function keys or using the displayed toolbar. As you use the IDE, you will find the method you feel most comfortable with

• The title bar area shows you the name of your project and the name of the form currently displayed. Also shown in brackets is one of three words: Design, Run or Break. This shows the mode Visual Basic .NET is operating in. Visual Basic .NET operates in three modes.

 Design mode - used to build application
 Run mode - used to run the application
 Break mode - application halted and debugger is available

We focus here on the design mode. You should, however, always be aware of what mode you are working in.


• Under the title bar is the Menu. This menu is dynamic, changing as you try to do different things in Visual Basic .NET. When you start working on a project, it should look like this:



You will become familiar with each menu topic as you work through the course. Briefly, they are:

File Use to open/close projects and files. Use to exit Visual Basic .NET
Edit Used when writing code to do the usual editing tasks of cutting, pasting, copying and deleting text
View Provides access to most of the windows in the IDE
Project Allows adding files and objects to your application
Build Allows you to compile and run your completed application (go to Run mode)
Debug Comes in handy to help track down errors in your code (works when Visual Basic .NET is in Break mode)
Data Used when building database applications (not covered in this course)
Format Useful for manipulating controls placed on your forms
Tools Allows custom configuration of the IDE. Be particularly aware of the Options choice under this menu item. This choice allows you to modify the IDE to meet any personal requirements.
Window Lets you change the layout of windows in the IDE
Help Perhaps, the most important item in the Menu. Provides access to the Visual Basic .NET on-line documentation via help contents, index or search. Get used to this item!

• The View menu also allows you to choose from a myriad of toolbars available in the Visual Basic .NET IDE. Toolbars provide quick access to many features. The Standard (default) toolbar appears below the Menu:







If you forget what a toolbar button does, hover your mouse cursor over the button until a descriptive tooltip appears. We will discuss most of these toolbar functions in the remainder of the IDE information.

• In the middle of the Visual Basic .NET IDE is the Design Window. This window is central to developing Visual Basic .NET applications. Various items are available by selecting tabs at the top of the window. The primary use is to draw your application on a form and, later, to write code. Forms are selected using the tab named FormName.vb [Design]:



The corresponding code for a form is found using the FormName.vb tab. The design window will also display help topics and other information you may choose.


• The Toolbox is the selection menu for controls used in your application. It is active when a form is shown in the design window. A divided view of the toolbox:



Many of these tools will look familiar to you. They are used in a wide variety of Windows applications you have used (the Visual Basic .NET IDE even uses them!) We will soon look at how to move a control from the toolbox to a form.


• The Properties Window is used to establish design mode (initial) property values for objects (controls). The drop-down box at the top of the window lists all objects in the current form. Two views are available: Alphabetic and Categorized (selection is made using menu bar under drop-down box). Under this box are the available properties for the active (currently selected) object. Help with any property can be obtained by highlighting the property of interest and pressing .





We will examine how to assign properties after placing some controls on a form.


• The Solution Explorer Window displays a list of all forms, modules and other files making up your application. To view a form in this window, simply double-click the file name. Or, highlight the file and press -. Or, you can obtain a view of the Form or Code windows (window containing the actual Basic coding) from the Project window, using the toolbar near the top of the window. As we mentioned, there are many ways to do things using the Visual Basic .NET IDE.



• Two windows useful when running an application are the Task List Window and Output Window. The task list window highlights any errors encountered while trying to run an application. The window will direct you to the line(s) of code with identified errors. The output window outlines the steps followed as an application is compiled.


• The help facilities of Visual Basic .NET are vast and very useful. As you work more and more with Visual Basic .NET, you will become very dependent on these facilities. Help is obtained using three different windows (all accessed using the Help menu item). The Index window is a list of topics you can obtain help on. Once selected from the menu, this window appears as a tab under the Solutions Explorer window:



Click on any topic to obtain help. The topic will appear as a separate tab in the Design window. You can navigate among any help pages you have opened using the familiar navigation toolbar that will appear:



The Search window (also a tab under the Solutions Explorer window) lets you search the help documentation using keywords. Related topics will be listed in an additional window.


• A great new feature of Visual Basic .NET is the idea of Dynamic Help. Once selected from the Help menu, this window appears as a tab under the Properties window:



This window will always displays topics deemed relevant to the current task at hand. The window above shows topics related to the Windows form since this is what is displayed in the Design window. Once controls are placed on the form, as you click from control to control, the contents of this window will change to topics appropriate to the selected (active) control. You will use this feature a lot – it saves a lot of time searching through other documentation.

• This completes our quick tour of the Visual Basic .NET IDE. We now turn our attention to building our first application using these three steps:

1. Draw the user interface (place controls on the form).
2. Set control properties
3. Write code




Drawing the User Interface

• The first step in developing a Visual Basic .NET Windows application is to draw the user interface on the form. Make sure the Form appears in the Design window. There are three ways to place controls on a form:

1. Double-click the tool in the toolbox and it is created with a default size on the form. It will be in the upper left corner of the form. You can then move it or resize it. Here is a button control placed on the form using this method:



2. Click the tool in the toolbox, then move the mouse pointer to the form window. The cursor changes to a crosshair. Place the crosshair at the upper left corner of where you want the control to be and click the left mouse button. The control will appear at the clicked point. Here is a default size button placed on the form using this technique:




3. Click the tool in the toolbox, then move the mouse pointer to the form window. The cursor changes to a crosshair. Place the crosshair at the upper left corner of where you want the control to be, press the left mouse button and hold it down while dragging the cursor toward the lower right corner. A rectangle will be drawn. When you release the mouse button, the control is drawn in the rectangle. A big button drawn using this method:



• To move a control you have drawn, click the object in the form (a cross with arrows will appear). Now, drag the control to the new location. Release the mouse button.

• To resize a control, click the control so that it is selected (active) and sizing handles appear. Use these handles to resize the object.



• To delete a control, select that control so it is active (sizing handles will appear). Then, press on the keyboard. Or, right-click the control. A menu will appear. Choose the Delete option. You can change your mind immediately after deleting a control by choosing the Undo option under the Edit menu.

Example 1-1

Stopwatch Application - Drawing Controls

1. Start a new project. The idea of this project is to start a timer, then stop the timer and compute the elapsed time (in seconds).

2. Place three buttons and six labels on the form. Move and size the controls and form so it looks something like this:



3. Save this project (saved in the Example 1-1 folder in LearnVBN\VBN Code\Class 1 folder). To save, simply click the Save All button in the toolbar. Visual Basic .NET does a good job of saving and maintaining all files associated with your projects. You rarely have to worry about the saving tasks.


Opening a Saved Visual Basic .NET Project

• Every example, problem and exercise presented in this course has an accompanying Visual Basic .NET solution folder. This lets you see how we did things. These folders are saved in the LearnVBN\VBN Code directory, sorted by chapter number. You need to know how to open these projects. And, you need to know how to open any projects you may have saved.

• Opening a previously saved Visual Basic .NET project is a simple task. Choose the File menu option in the Visual Basic .NET IDE and select Open. Then, choose Project. The Open Project dialog box will appear. Open the Open the desired project folder and you see:



• At this point, click on the Solution file and click Open. Or, double-click the Solution file. All the components of your project will be assembled and displayed. It’s that easy!



Setting Properties of Controls at Design Time

• Each form and control has properties assigned to it by default when you start up a new project. There are two ways to display the properties of an object. The first way is to click on the object (form or control) in the form window. Sizing handles will appear on that control. When a control has sizing handles, we say it is the active control. Now, click on the Properties window or the Properties window button in the tool bar. The second way is to first click on the Properties window. Then, select the object from the drop-down box at the top of the Properties window. When you do this, the selected object (control) will now be active (have sizing handles). Shown is the Properties window for the stopwatch application (for the Form object):



• The drop-down box at the top of the Properties Window is the Object box. It displays the name of each object in the application as well as its type. This display shows the Form object. The Properties list is directly below this box. In this list, you can scroll through the list of properties for the selected object. You select a property by clicking on it. Properties can be changed by typing a new value or choosing from a list of predefined settings (available as a drop down list). Properties can be viewed in two ways: Alphabetic and Categorized (selected using the menu bar under the Object box). At the bottom of the Properties window is a short description of the selected property (a kind of dynamic help system).


• A very important property for each control is its Name. The name is used by Visual Basic .NET to refer to a particular object or control in code. A convention has been established for naming Visual Basic .NET controls. This convention is to use a three letter (lower case) prefix (identifying the type of control) followed by a name you assign. A few of the prefixes are (we’ll see more as we progress in the class):

Control Prefix Example
Form frm frmWatch
Button btn btnExit, btnStart
Label lbl lblStart, lblEnd
Text Box txt txtTime, txtName
Menu mnu mnuExit, mnuSave
Check box chk chkChoice

Even though the names we have used in these examples have both lower and upper case letters, Visual Basic .NET is case-insensitive. Hence, the names frmWatch and FRMWATCH would be assumed to be the same name.

• Control (object) names can be up to 40 characters long, must start with a letter, must contain only letters, numbers, and the underscore (_) character. Names are used in setting properties at run-time and also in establishing procedure names for control events. Use meaningful names that help you (or another programmer) understand the type and purpose of the respective controls.


• Another set of important properties for each control are those that dictate position and size. There will be times you want to refer to (or change) these properties. There are four properties:

Left Distance from left side of form to left edge of control, in pixels
Top Distance from title bar of form to top edge of control, in pixels
Width Width of control, in pixels
Height Height of control, in pixels

Pictorially, these properties for a button control are:




Setting Properties at Run Time

• In addition to setting properties at design time, you can set or modify properties while your application is running. To do this, you must write some code. The code format is:

ObjectName.PropertyName = NewValue

Such a format is referred to as dot notation. For example, to change the BackColor property of a button named btnStart, we'd type:

btnStart.BackColor = Color.Blue

• You’ve just seen your first line of code in Visual Basic .NET. Good naming conventions make it easy to understand what’s going on here. The button named btnStart will now have a blue background. We won’t learn much code in this first chapter (you’ll learn a lot in Chapter 2), but you should see that the code that is used is straightforward and easy to understand.

How Names are Used in Control Events

• The names you assign to controls are also used by Visual Basic .NET to set up a framework of event-driven procedures for you to add code to. Hence, proper naming makes these procedures easier to understand.

• The format for each of these procedures, or subroutines (all event procedures in Visual Basic .NET are subroutines), is:

Private Sub ControlName_Event (Arguments) Handles ControlName.Event
.
.
End Sub

where Arguments provides information needed by the procedure to do its work.

• Visual Basic .NET provides the Sub line with its arguments and the End Sub statement. You provide any needed code. Don’t worry about how to provide this code right now. Just notice that with proper naming convention, it is easy to identify what tasks are associated with a particular event of a particular control.



Example 1-2

Stopwatch Application - Setting Properties

1. Continue with Example 1-1. Set properties of the form, three buttons, and six labels:

Form1:
Name frmStopWatch
FormBorderStyle Fixed Single
StartPosition CenterScreen
Text Stopwatch Application

Button1:
Name btnStart
Text &Start Timing

Button2:
Name btnEnd
Text &End Timing

Button3:
Name btnExit
Text E&xit

Label1:
Text Start Time

Label2:
Text End Time

Label3:
Text Elapsed Time (sec)

Label4:
Name lblStart
BorderStyle Fixed3D
Text [Blank]

Label5:
Name lblEnd
BorderStyle Fixed3D
Text [Blank]


Label6:
Name lblElapsed
BorderStyle Fixed3D
Text [Blank]

In the Text properties of the three buttons, notice the ampersand (&). The ampersand precedes a button's access key. That is, in addition to clicking on a button to invoke its event, you can also press its access key (no need for a mouse). The access key is pressed in conjunction with the Alt key. Hence, to invoke 'Start Timing', you can either click the button or press +S. Note in the button text on the form, the access keys appear with an underscore (_).

2. Your form should now look something like this:



3. Save this project (Example 1-2 folder in LearnVBN\VBN Code\Class 1 folder).


Writing Code

• The last step in building a Visual Basic .NET application is to write code using the BASIC language. This is the most time consuming task in any Visual Basic .NET application. It is also the most fun and most rewarding task.

• As controls are added to a form, Visual Basic .NET automatically builds a framework of all event procedures. We simply add code to the event procedures we want our application to respond to. And, if needed, we write general procedures. For those who may have never programmed before, the code in these procedures is simply a line by line list of instructions for the computer to follow. A useful feature when working with code is to put line numbers next to each line of code (helps identify any errors you may make). To do this, select the Tools menu item in the IDE. Then, choose Options. In the left side of the window that appears, choose Text Editor (and perhaps Basic). Then, choose the Line Numbers option.

• Code is placed in the Code Window. Typing code in the code window is just like using any word processor. You can cut, copy, paste and delete text (use the Edit menu or the toolbar). Learn how to access the code window using the menu (View), toolbar, or by pressing (and there are still other ways) while the form is active. Here is the Code window for the stopwatch application we are working on:




• Wait! This window shows there are 142 lines of code already and we haven’t done anything! What’s going on? The code that is there is code prepared by Visual Basic .NET just to make the form, buttons and label appear. To see all the code, click on the little (+) next to the Windows Form Designer generated code line. Scroll through the code to see what it looks like. Now, click on the (-) sign to once again hide this code. Always leave this code hidden; we will not look at it again. Experienced programmers actually modify this generated code for certain purposes. We won’t be touching it! All code we develop will go in the Code window after the ‘boxed’ Windows Form Designer generated code line (or starting at Line 140 in this example).

• At the top of the code window are two boxes, the object (or control) list on the left and the procedure list on the right. Select an object and the corresponding event procedure. A blank procedure will appear in the window where you write BASIC code. For the stopwatch project, the btnStart Click event procedure appears as:

Private Sub btnStart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnStart.Click
.
.
End Sub

Let’s spend some time looking at this procedure – all event procedures used in Visual Basic .NET look just like this. The time spent clarifying things now will be well worth it.

• The assigned name for the event procedure is seen to be btnStart_Click. Our naming convention tells us this is the procedure executed when the user clicks on the btnStart button. The procedure has two arguments: sender and e. Sender tells the procedure what control caused the Click event to occur and e gives us some information about the event. Now, notice the Handles keyword:

Handles btnStart.Click


This tells us that his procedure Handles the Click event for btnStart. You might ask – didn’t the name of the procedure (btnStart_Click) tell us the same thing? Isn’t the Handles clause redundant? The answer is No. The name of the procedure is arbitrary (you can change it if you want and sometimes we want to). The Handles clause tells us what event has to occur for the procedure to be invoked. In fact, in later classes, we will see how to attach multiple events to a single procedure. That’s why the sender argument is there – to tell us which control (in a multiple control scenario) caused the event to occur. We will learn much more about this later.

• Another way to make an event procedure appear is to double-click on a control. Try it. An event procedure (one deemed most ‘likely’ by Visual Basic .NET) will appear. The problem with this technique is that the procedure that appears may not be the event procedure you desire. You can decide which way of generating event procedures is most suitable for your needs.



Variables

• We’re now ready to write code for our application. As just seen, as controls are added to the form, Visual Basic .NET builds a framework of event procedures. We simply add code to the event procedures we want our application to respond to. But before we do this, we need to discuss variables.

• Variables are used by Visual Basic .NET to hold information needed by an application. Variables must be properly named. Rules used in naming variables:

 No more than 40 characters
 They may include letters, numbers, and underscore (_)
 The first character must be a letter
 You cannot use a reserved word (keywords used by Visual Basic .NET)

Use meaningful variable names that help you (or other programmers) understand the purpose of the information stored by the variable.

• Examples of acceptable variable names:

StartingTime Interest_Value Letter05
JohnsAge Number_of_Days TimeOfDay



Visual Basic .NET Data Types

• Each variable is used to store information of a particular type. Visual Basic .NET has a wide range of data types. You must always know the type of information stored in a particular variable.

• Boolean variables can have one of two different values: True or False (reserved words in Visual Basic .NET). Boolean variables are helpful in making decisions.

• If a variable stores a whole number (no decimal), there are three data types available: Short, Integer or Long. Which type you select depends on the range of the value stored by the variable:

Data Type Range
Short -32,678 to 32,767
Integer -2,147,483,648 to 2,147,483,647
Long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

We will almost always use the Integer type in our work.

• If a variable stores a decimal number, there are two data types: Single or Double. The Double uses twice as much storage as Single, providing more precision and a wider range. Examples:

Data Type Value
Single 3.14
Double 3.14159265359

• Visual Basic .NET is a popular language for performing string manipulations. These manipulations are performed on variables of type String. A string variable is just that - a string (list) of various characters. In Visual Basic .NET, string variable values are enclosed in quotes. Examples of string variables:

“Visual Basic .NET” “012345” “Title Author”


• Visual Basic .NET also has great facilities for handling dates and times. The Date variable type stores both dates and times. Using different formatting techniques (we will learn these) allow us to display dates and times in any format desired.

• A last data type is type Object. That is, we can actually define a variable to represent any Visual Basic .NET object, like a button or form. We will see the utility of the Object type as we progress in the course.

Variable Declaration

• Once we have decided on a variable name and the type of variable, we must tell our Visual Basic .NET application what that name and type are. We say, we must explicitly declare the variable.

• It is possible to use Visual Basic .NET without declaring variables, but this is a dangerous practice There are many advantages to explicitly typing variables. Primarily, we insure all computations are properly done, mistyped variable names are easily spotted, and Visual Basic .NET will take care of insuring consistency in variable names. Because of these advantages, and because it is good programming practice, we will always explicitly type variables. To insure variable typing is checked, we will always add this single line:

Option Explicit On

to the top of every application’s code:



• To explicitly type a variable, you must first determine its scope. Scope identifies how widely disseminated we want the variable value to be. We will use four levels of scope:

 Procedure level
 Procedure level, static
 Form and module level
 Global level


• The value of procedure level variables are only available within a procedure. Such variables are declared within a procedure using the Dim statement:

Dim MyInt as Integer
Dim MyDouble as Double
Dim MyString As String, YourString as String

Procedure level variables declared in this manner do not retain their value once a procedure terminates.

• To make a procedure level variable retain its value upon exiting the procedure, replace the Dim keyword with Static:

Static MyInt as Integer
Static MyDouble as Double

• Form (module) level variables retain their value and are available to all procedures within that form (module). Form (module) level variables are declared in the code window right after the code generated automatically be Visual Basic .NET (the Windows Form Designer generated code).



The Dim keyword is used to declare form (module) level variables:

Dim MyInt as Integer
Dim MyDate as Date


• Global level variables retain their value and are available to all forms, modules and procedures within an application. Such variables can only be declared in a code module – a separate project component (discussed in Chapter 5). Global level variables are declared in a module's code window prior to any procedure. (It is advisable to keep all global variables in one module.) Use the Public keyword:

Public MyInt as Integer
Public MyDate as Date

• What happens if you declare a variable with the same name in two or more places? More local variables shadow (are accessed in preference to) less local variables. For example, if a variable MyInt is defined as Public in a module and declared local in a routine MyRoutine, while in MyRoutine, the local value of MyInt is accessed. Outside MyRoutine, the global value of MyInt is accessed.

• Example of Variable Scope:

Module1
Public X as Integer

Form1 Form2
Dim Y as Integer Dim Z as Single

Sub Routine1() Sub Routine3()
Dim A as Double Dim C as String
. .
. .
End Sub End Sub

Sub Routine2()
Static B as Double
.
.
End Sub


Procedure Routine1 has access to X, Y, and A (loses value upon termination)
Procedure Routine2 has access to X, Y, and B (retains value)
Procedure Routine3 has access to X, Z, and C (loses value)


Arrays

• Visual Basic .NET has powerful facilities for handling arrays, which provide a way to store a large number of variables under the same name. Each variable, called an element, in an array must have the same data type, and they are distinguished from each other by an array index. In this class, we work with one-dimensional arrays, although multi-dimensional arrays are possible.

• Arrays are declared in a manner identical to that used for regular variables. For example, to declare an integer array named 'Item', with dimension 9, at the procedure level, we use:

Dim Item(9) as Integer

If we want the array variables to retain their value upon leaving a procedure, we use the keyword Static:

Static Item(9) as Integer

At the form or module level, in the proper region of the Code window, use:

Dim Item(9) as Integer

And, at the global level, in a code module, use:

Public Item(9) as Integer

• The index on an array variable begins at 0 and ends at the dimensioned value. Hence, the Item array in the above examples has ten elements, ranging from Item(0) to Item(9). You use array variables just like any other variable - just remember to include its name and its index. Many times, the 0 index is ignored and we just start with item 1. But sometimes (especially when working with Visual Basic .NET controls) the 0th element cannot be ignored. You will see examples of both 0-based and 1-based arrays in the course examples.

• It is also possible to have arrays of controls. For example, to have 20 button types available use:

Dim MyButtons(19) as Button

The utility of such a declaration will become apparent in later classes.



Constants

• You can also define constants for use in Visual Basic .NET. The format for defining a constant named NumberOfUses with a value 200 is:

Const NumberOfUses As Integer = 200

• The scope of user-defined constants is established the same way a variables’ scope is. That is, if defined within a procedure, they are local to the procedure. If defined in the top region of a form’s code window, they are global to the form. To make constants global to an application, use the format:

Public Const NumberOfUses As Integer = 200

within a code module.


Variable Initialization

• By default, any declared numeric variables are initialized at zero. String variables are initialized at an empty string. If desired, Visual Basic .NET lets you initialize variables at the same time you declare them. Just insure that the type of initial value matches the variable type (i.e. don’t assign a string value to an integer variable).

• Examples of variable initialization:

Dim MyInt as Integer = 23
Dim MyString as String = “Visual Basic .NET”
Static MyDouble as Double = 7.28474746464
Public MyDate as Date = #1/2/2001#

• You can even initialize arrays with this technique. You must, however, delete the explicit dimension (number of elements) and let Visual Basic .NET figure it out by counting the number of elements used to initialize the array. An example is:

Dim Item() as Integer = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

Visual Basic .NET will know this array has 10 elements (a dimension of 9).


Intellisense Feature

• Yes, we’re finally ready to start writing some code in the code window. You will see that typing code is just like using any word processor. The usual navigation and editing features are all there.

• One feature that you will become comfortable with and amazed with is called Intellisense. As you type code, the Intellisense feature will, at times, provide assistance in completing lines of code. For example, once you type a control name and a dot (.), a drop-down list of possible properties and methods will appear. When we use functions and procedures, suggested values for arguments will be provided. Syntax errors will be identified. And, potential errors with running an application will be pointed out.

• Intellisense is a very useful part of Visual Basic .NET. You should become acquainted with its use and how to select suggested values. We tell you about now so you won’t be surprised when little boxes start popping up as you type code.

• Let’s finally complete the stopwatch application. We’ll just give you the code. Don’t worry about where it comes from for now. You’ll learn a lot about coding as you venture forth in this course. Just type the code as given – you should see how easy it is to understand however.

Example 1-3

Stopwatch Application - Writing Code

All that’s left to do is write code for the application. We write code for every event a response is needed for. In this application, there are three such events: clicking on each of the buttons.

1. Double-click anywhere on the form to open the code window. Or, select ‘View Code’ from the project window. Or, press while the form is active.

2. At the very top of the code window, type this line (to enforce explicit variable declaration):

Option Explicit On

3. Under the line marked Windows Form Designer generated code declare three form level variables:

Dim StartTime As Date
Dim EndTime As Date
Dim ElapsedTime As Integer

This establishes StartTime, EndTime, and ElapsedTime as variables with form level scope. At this point, the Code window should look like this:



4. Select the btnStart object in the Object box of the code window. Choose Click from the procedure box. Or, try double-clicking the button control. Type the following code which begins the timing procedure. Note the Sub and End Sub statements are provided for you:

Private Sub btnStart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnStart.Click
'Establish and print starting time
StartTime = Now
lblStart.Text = Format(StartTime, "hh:mm:ss")
lblEnd.Text = ""
lblElapsed.Text = ""
End Sub

In this procedure, once the Start Timing button is clicked, we read the current time and print it in a label box. We also blank out the other label boxes. In the code above (and in all code in these notes), any line beginning with a single quote (‘) is a comment. You decide whether you want to type these lines or not. They are not needed for proper application operation.

5. Now, select the btnEnd object in the Object box. Choose Click from the procedure box. Add this code:

Private Sub btnEnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnd.Click
'Find the ending time, compute the elapsed time
'Put both values in lable boxes
EndTime = Now
ElapsedTime = DateDiff(DateInterval.Second, StartTime, EndTime)
lblEnd.Text = Format(EndTime, "hh:mm:ss")
lblElapsed.Text = Format(ElapsedTime, "0")
End Sub

Here, when the End Timing button is clicked, we read the current time (End Time), compute the elapsed time, and put both values in their corresponding label boxes.


6. Finally, select the btnExit object in the Object box. Choose Click from the procedure box. That button’s Click event code:

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub

This routine simply closes the form (identified by the keyword Me) once the Exit button is clicked.

7. Did you notice as you typed in the code, how the Intellisense feature of Visual Basic .NET worked? Run your application by clicking the Start button on the toolbar, or by pressing . Pretty easy, wasn’t it? If you application doesn’t run, recheck to make sure the code is typed properly. Save your application. This is saved in the Example 1-3 folder in LearnVBN\VBN Code\Class 1 folder.

If you have the time, some other things you may try with the Stopwatch Application:

A. Try changing the form color and the fonts used in the label boxes and buttons.

B. Notice you can press the ‘End Timing’ button before the ‘Start Timing’ button. This shouldn’t be so. Change the application so you can’t do this. And make it such that you can’t press the ‘Start Timing’ until ‘End Timing’ has been pressed. Hint: Look at the button Enabled property.

C. Can you think of how you can continuously display the ‘End Time’ and ‘Elapsed Time’? This is a little tricky because of the event-driven nature of Visual Basic .NET. Look at the Timer control. By setting the Interval property of this control to 1000 and the Enabled property to True, it will generate its own events (the Tick event) every one second. Put code similar to that in the btnEnd_Click event in the Timer control’s Tick event and see what happens. Also, see the exercise at the end of the class for help on this one. The Timer control will not appear on the form, but in a ‘tray’ below the form. This happens because the Timer control has no user interface.


Class Review

• After completing this class, you should understand:

 The concept of an event-driven application
 What object-oriented programming (OOP) is about
 The parts of a Visual Basic .NET application (form, control, property, event, …)
 The various windows of the Visual Basic .NET integrated development environment
 How to use the Visual Basic .NET on-line help system
 The three steps in building a Visual Basic .NET application
 Three ways to place controls on a form
 Methods to set properties for controls
 Proper control naming convention
 Proper variable naming and typing procedures
 The concept of variable scope
 How to properly declare a variable
 How to define a constant
 How to add code and declarations using the code window
 Ways to use the Intellisense feature when typing code




Practice Problems 1*

Problem 1-1. Beep Problem. Build an application with a single button. When the button is clicked, make the computer beep (use the Beep function).

Problem 1-2. Text Problem. Build an application with a single button. When the button is clicked, change the button’s Text property. This allows a button to be used for multiple purposes. If you want to change the button caption back when you click again, you’ll need an If statement. We’ll discuss this statement in the next class, but, if you’re adventurous, look in on-line help to try it.

Problem 1-3. Enabled Problem. Build an application with two buttons. When you click one button, make it disabled (Enabled = False) and make the other button enabled (Enabled = True).

Problem 1-4. Date Problem. Build an application with a button. When the button is clicked, have the computer display the current date in a label control.




*Note: Practice Problems are given after each class to give you practice in writing code for your Visual Basic .NET applications. These are meant to be quick and, hopefully, short exercises. The Visual Basic .NET environment makes it easy to build and test quick applications – in fact, programmers develop such examples all the time to test some idea they might have. Use your imagination in working the problems – modify them in any way you want. You learn programming by doing programming! The more you program, the better programmer you will become. Our solutions to the Practice Problems are provided as an addenda to these notes.


Exercise 1*

Calendar/Time Display

Design a window that displays the current month, day, and year. Also, display the current time, updating it every second (look into the Timer control). Make the window look something like a calendar page. Play with control properties to make it pretty.




*Note: After completing each class’ notes, a homework exercise (and, sometimes, more) is given, covering many of the topics taught. Try to work through the homework exercise on your own. This is how programming is learned – solving a particular problem. For reference, solutions to all Exercises are provided as an addenda to these notes. In our solutions, you may occasionally see something you don’t recognize. When this happens, use the on-line help system to learn what’s going on. This is another helpful skill – understanding other people’s applications and code.




















Tidak ada komentar:

Posting Komentar