Documentation

Page 1

Norton University

Faculty of Computer Science

Visual Basic Programming Objectives: Visual Basic Introduction, OOP or equivalent skills. Windows programming experience with a structured language is required. By the end of this course

students will be able to: - Creating a Simple Application. - Negotiate the elements in Visual Basic.net to suite the customer needs. - Using problem solving especially in Visual Basic.net Language.

Table of contents Chapter Week Introduction VB.NET 1

Description

2,3

4

5, 6 7

8 9 10

17

Class Modules Subroutine Functions

Window Controls V

15

Test Structures Loop Structures Nested Control Structures

Creating Class Modules and Using Procedures IV

7

Variables Type of Variable Converting Variable types User-Defined Data types Variable‘s Scope Constants Arrays Structured Exception Handling

Control Flow III

3

What‘s .NET?

VB Language I

Page

29

Text Box List Box and Combo box Common dialog Controls

Text Files VI

11, 12, 13 14 15,16

File Access - Sequential - Random - Binary Revision (Q & A) Define Assignments

Research and Academic Affairs

38


Visual Basic .NET

Assignment: 5 % for Class Participation 15 % for Mid-Term 20 % for Assignment 60 % for Semester Examination 100 % for Semester Total Scores References: 

Mastering Visual Basic .NET

Author: Evangelos Petroutsos ISBN: 0-7821-2877-7, Copyright 2001 by SYBEX Inc 

VB.NET Developer‘s Guide

By: Cameron Wakefield, Henk-Evert Sonder, Wei Meng Lee ISBN: 1-928994-48-2, Copyright 2001 by Syngress Publishing, Inc. 

VB .NET Language in a Nutshell

By: Steven Roman, Ron Petrusha, Paul Lomax Publisher: O'Reilly First Edition August 2001 ISBN: 0-596-00092-8 

Online: - http://msdn.microsoft.com/library/ - http://www.microsoft.com/net/

Phnom Penh, October 01, 2012 Signature

Hoeung Rathsokha

Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/

2


Prepared by Hoeung Rathsokha

Introduction VB.NET

Introduction Everyone, I‘m sure, who has allowed for more than a passing perusal of .net must be excited at the power of it framework. Those with a pure programming background and earlier knowledge of pre-.net technologies have found those to be sorely lacking in the solidity and methodology of pure of OOP environment and or language. What I will aim at achieving in this article is to get all NON-OOP programmers up to speed with this whole brave new world of thinking when programming. Making an allowance for terms such as Classes, Objects, Properties, Structures, Overloading, inheritance, abstraction, and Polymorphism can seem unapproachable to non-seasoned programmers with insufficient OOP awareness. OOP: Object Oriented Programming is the concept of programming with objects. There are two good reasons why you would love programming OOP objects. One is that you have full control over how anyone would use the object you created, and two, encapsulation, in other words you hard earned OOP code is protected and hidden from everyone. No one could modify it or change it, certainly anyone not qualified. They simply are available for a specific use, and this is key. Want to know more about how you can move your company to the latest generation of Microsoft connected technology? Here's how you can start building .NET-connected systems. What Is .NET? Microsoft .NET is a set of software technologies for connecting information, people, systems, and devices. This new generation of technology is based on Web services—small building-block applications that can connect to each other as well as to other, larger applications over the Internet. .NET Framework The .NET Framework is an environment for building, deploying, and running XML Web services and other applications. It is the infrastructure for the overall .NET platform. The .NET Framework consists of three main parts: the common language runtime, the class libraries, and ASP.NET. The common language runtime and class libraries, including Windows Forms, ADO.NET, and ASP.NET, combine to provide services and solutions that can be easily integrated within and across a variety of systems. The .NET Framework provides a fully managed, protected, and feature-rich application execution environment, simplified development and deployment, and seamless integration with a wide variety of languages. ASP.NET is more than the next version of Active Server Pages (ASP); it is a unified Web development platform that provides the services necessary for developers to build enterprise-class Web applications. ADO.NET is a set of classes that expose the data access services of the .NET Framework. ADO.NET is a natural evolution of ADO and is built around N-Tier application development. ADO.NET has been created with XML at its core. The ADO.NET object model is composed of two central components: the connected layer, which consists of the classes that comprise the .NET Data Provider, and the disconnected layer, which is rooted in the DataSet. .NET Data Providers includes the following components:

Object Connection Command DataReader DataAdapter

Description Establishes a connection to a specific data source. Executes a command against a data source. Reads a forward-only, read-only stream of data from a data source. Populates a DataSet and resolves updates with the data source.

Research and Academic Affairs

Batchelor Course

3


Visual Basic .NET

Comparison of the .NET Framework Data Provider for SQL Server and the .NET Framework Data Provider for OLE DB

XML Web service is a unit of application logic providing data and services to other applications. XML Web services can be accessed by any language, using any component model, running on any operating system. Namespaces.NET furthers the scope of OOP by compartmentalizing objects within namespaces, as an excellent means of categorizing and personalizing common and related fields, classes, structs/Structures or interfaces as a collection, as well as other namespaces known as nested namespaces! When including namespaces in application, VB uses the “Imports� keyword. Ex. Imports System

1. Classes Is a create object. In more detail, a class is a reference type (that which store some type of information) that encapsulates (hides or encloses) and or modularizes (making for flexible, varied use) any amount of methods (subroutines/functions), fields, variable or Properties or constructors (object creating function) that classified data and performs some kind of functionality. Ex.

Compile your source ClassLibrary1.sln file into a DLL. Click Build CalssLibrary1 from Build menu.

Or paste this code in notepad and save as House.vb and Open Visual Studio .NET Command Prompt then type:

vbc /t:library /out:c:\house.dll house.vb /optimize Where: /t:library or /target:library Create a library assembly. /out:c:\hous.dll Specifies the output file name. /optimize[+|-] Code Generation Enable optimizations.

Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/

4


Prepared by Hoeung Rathsokha Introduction VB.NET Now that we have the materials for our house let‘s build one Blueprint house if I may. In VB code Dim Hse As New House With Hse .HseOwner = "Miss. Rachna" .HseSize = "Huge" .HseColor = "Blue" End With MsgBox(Hse.Information) Hse = Nothing Or place the code below in a house.aspx, then run it in your browser. <%@ Language=VBScript %> <html> <body> <Script language="vb" runat="server" > Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim Hse As New House With Hse .HseOwner = "Miss. Rachna" .HseSize = "Huge" .HseColor = "Blue" End With Response.Write(Hse.Information) Hse = Nothing 'Clear the object End Sub </Script> </body> </html>

2. Properties Properties are a natural extension of variables; both are named members with associated types, and the syntax for accessing variables and properties is the same. Unlike variables, however, properties do not denote storage locations. Public Class House Private HseOwner As String Public HseSize As String Public HseColor As String Public Property ShowOwner() As String Get Return HseOwner End Get Set(ByVal Value As String) HseOwner = Value End Set End Property Private Property ShowColor() As String Get If (HseColor = "red") Then Return HseColor & ". But I'll Change it to White." Else Return HseColor End If End Get Set(ByVal Value As String) HseColor = Value End Set End Property Public Function Information() As String Return ShowOwner & " has a new house that's " & _ HseSize & ", and is painting it " & ShowColor End Function

Research and Academic Affairs

Batchelor Course

5


Visual Basic .NET End Class And Change as: Dim Hse As New House With Hse .ShowOwner = "Miss. Rachna" .HseSize = "Huge" .HseColor = "red" End With MsgBox(Hse.Information) Hse = Nothing

Conclusion In conclusion, beyond all we‘ve touched upon, OOP can be quit extensive in its depth and conceptual methodologies. There is far more that can be learned, including everything from sealed and non-inheritable classes to delegates and events and so forth, to say the least. Still, the foundation we‘ve set forth I hope is an excellent start and overview of OOP for you. There are many of great resources found online or at the end of this book that would allow you a deeper look into the illimitable complexities and structures of OOP. Yet, learning on these concepts is best accomplished like most things in development, having something to make use of them in and performing real-world work. In Close, my objective here was to introduce a direct and to the point outline of OOP that should now have given you a firm place to stand on from which you now could plan your next move on the road to object-oriented application development.

Until next time, happy .NETing! Mr. Hoeung Rathsokha (BSc. In Civil & Industrial of Construction, BSc. In computer, and MSCIM)

Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/

6


Prepared by Hoeung Rathsokha

Introduction VB.NET

The VB Language Hello Example: - Open text editor and code follow: 0. ' A "Hello World!" program in Visual Basic. 1. Module Hello 2. Sub Main() 3. MsgBox("Hello World!") ' Display message on computer screen. 4. End Sub 5. End Module - And save it with a file name Hello.vb The important points of this program are the following: 

Comments



The Main procedure



Input and output



Compilation and execution

Compilation and Execution You can compile the "Hello World!" program using either the Visual Studio .NET integrated development environment (IDE) or the command line. To compile and run the program from the command line 1. Create the source file using any text editor and save it with a file name such as Hello.vb. 2. To invoke the compiler, enter the following command: vbc Hello.vb 3. If your program does not contain any compilation errors, the compiler creates a Hello.exe file. 4. To run the program, enter the following command: Hello To compile and run the program from the IDE 1. Create a Visual Basic console application project. 2. Copy the code into the project. 3. Choose the appropriate Build command from the Build menu, or F5 to build and run (corresponding to Start in the Debug menu).

___----~~~~~ ‘‘‘‘‘WELCOME TO VISUAL BASIC.NET‘‘‘‘‘~~~~~------___

Research and Academic Affairs

Batchelor Course

7


Visual Basic .NET Variables Type of Variable Converting Variable types User-Defined Data types Variable’s Scope Constants Arrays

__________________________________________________________ Variables In Visual Basic, as in any other programming language, Variable has a name and a value; Variables store values during a program‘s execution. When a variable‘s value is a string, it must be enclosed in double quotes. Or a variable that holds dates must be declared then you can assign a date to the variable like this: mdy = #10/1/2012# Declaring Variables

When you declare variables in your code, you‘re actually telling the compiler of the type of data you intend to store in each variable. To declare a variable, use the Dim statement followed by the variable’s name, the As keyword, and its type, as follows: Dim meters As Integer When declaring variables, you should be aware of a few naming conventions. A variable name: 1

Must begin with a letter.

2

Can‘t contain embedded periods.

3

Mustn‘t exceed 255 characters.

4

Must be unique within its scope

Variable names in VB.NET are case-insensitive. Variable Initialization

You can also initialize variables in the same line that declares them. Example Dim distance As Integer = 3045 Or Dim distance As Integer distance = 3045 * If you want to declare multiple variables of the same type: Dim length, width As Integer, volume, area As Double * Another interesting new feature introduced with VB.NET (+=, -=, *=, /=, \=, &=): Counter = Counter + 1  is equivalent to Counter += 1 Result = Result + Counter  is equivalent to Result += Counter

Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/

8


Introduction VB.NET

Prepared by Hoeung Rathsokha

Type of Variables In VB.NET recognizes the following five categories of variables: 1

Numeric (store number): Integer, Decimal, Single, Double

2

String (store nearly 2GB of text)

3

Boolean(store -1: True/ 0: False)

4

Date (store Date and Time values)

5

Object (store any type of data)

Converting Variable Types Function

Converts its argument to

CBool

Boolean

CByte

Byte

CChar

Unicode Character

CDate

Date

CDbl

Double

CDec

Decimal

CShort

Short (Int16)

CInt

Integer (Int32)

CLng

Long (Int64)

CObj

Object

CSng

Single

CStr

String

The following table shows the Visual Basic .NET data types, their supporting common language runtime types, their nominal storage allocation, and their value ranges.

Boolean Byte Char Date

Common language runtime type structure System.Boolean System.Byte System.Char System.DateTime

Decimal

System.Decimal

Visual Basic type

Research and Academic Affairs

Nominal storage Value range allocation 2 bytes True or False. 1 byte 0 through 255 (unsigned). 2 bytes 0 through 65535 (unsigned). 8 bytes 0:00:00 on January 1, 0001 through 11:59:59 PM on December 31, 9999. 16 bytes 0 through +/79,228,162,514,264,337,593,543,950,335 with no decimal point; 0 through +/7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest Batchelor Course

9


Visual Basic .NET

Double (doubleprecision floatingpoint) Integer Long (long integer) Object

System.Double

Short Single (singleprecision floatingpoint) String (variablelength) UserDefined Type (structure)

System.Int16 System.Single

System.Int32 System.Int64

System.Object (class)

nonzero number is +/-0.0000000000000000000000000001 (+/-1E28). 8 bytes -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values; 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values. 4 bytes -2,147,483,648 through 2,147,483,647. 8 bytes -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. 4 bytes Any type can be stored in a variable of type Object. 2 bytes -32,768 through 32,767. 4 bytes -3.4028235E+38 through -1.401298E-45 for negative values; 1.401298E-45 through 3.4028235E+38 for positive values.

System.String (class) Depends on implementing platform (inherits from Depends on System.ValueType) implementing platform

0 to approximately 2 billion Unicode characters.

Each member of the structure has a range determined by its data type and independent of the ranges of the other members.

User-Defined Data Types A structure for storing multiple values (of the same or different type) is called a RECORD. To define a record in VB.NET, use the structure statement, which has the following syntax:

Structure StructName Dim Variable1 As VarType …………………………… Dim VariableN As VarType End Structure Where: - VarType: can be any of the data types support by the framework. To declare variables of this new type, use a statement such as this one: Dim VarName As StructName

10 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Prepared by Hoeung Rathsokha

Introduction VB.NET

Variable’s Scope The scope or visibility of a variable is the section of the application that can see and manipulate the variable.

Block-level: Variables introduced in a block of code within the procedure. Ex: Dim i, Sum As Integer For i = 0 to 100 Step 2 Dim SqrVal As Integer SqrVal = i * i Sum += SqrVal Next Procedure-level (local): it‘s visible within the procedure and invisible outside the procedure. Module-level: Variables declared outside any procedure in a module are visible from within all procedures in the same module, but they‘re in visible outside the module. Public-level (Global): The variable must be declared as public, they are visible from any part of the application.

Constants Syntax: Const ConstantName As Type = Value Ex. Public Const pi As Double = 3.141592 Const pi2 As Double = 2 * pi Constants are preferred for two reasons: 1. Constants don‘t change value. 2. Constants are processed faster then variables. When the program is running, the values of constants don‘t have to be looked up. The compiler substitutes constant names with there values, and the program execute faster.

Arrays A standard structure for storing data in any programming language is the array. Variables can hold single entities, such as one number, one date, or one string, ARRAY can hold sets of data of the same type. Array has a name, as does a variable, and the values stored in it can be accessed by an index. Declaring Arrays

Dim Salary(5) As Single ‗Array Limits Dim Colors() As Color = {Color.Red, Color.Green, Color.Blue, Color.White} ‘Initialize Arrays Dim Name() As String ‘Dynamic Arrays, you must use the ReDim statement to redimension of number of elements in the array. ReDim Name(UserCount) As String. Dim Data(9, 9, 9) As Single ‗Multidimensional Arrays. Dim a(,) As integer = {{10, 12}, {11, 13}, {15, 20}}

Research and Academic Affairs

Batchelor Course 11


Visual Basic .NET Arrays of Arrays

Arrays are a major part of the language. If an array is declared as object, you can assign other types to its elements, including arrays. Dim InArr(9) As Integer Dim StrArr(9) As String Dim BigArr(1) As Object ……………Assing value to Variable InArr, StrArr…………… BigArr(0) = InArr BigArr(1) = StrArr

Structured Exception Handling Visual Basic supports structured exception handling, which helps you create and maintain programs with robust, comprehensive error handlers. Structured exception handling is code designed to detect and respond to errors during execution by combining a control structure (similar to Select Case or While) with exceptions, protected blocks of code, and filters. Using the Try...Catch...Finally statement, you can protect blocks of code that have the potential to raise errors. You can nest exception handlers, and the variables declared in each block will have local scope. The Try...Catch...Finally Statement The following code shows the structure of a Try...Catch...Finally statement: Try ' Starts a structured exception handler. ' Place executable statements that may generate ' an exception in this block. Catch [optional filters] ' This code runs if the statements listed in ' the Try block fail and the filter on the Catch statement is true. [Additional Catch blocks] Finally ' This code always runs immediately before ' the Try statement exits. End Try ' Ends a structured exception handler.

The Try block of a Try...Catch...Finally exception handler contains the section of code you want your error handler to monitor. If an error occurs during execution of any of the code in this section, Visual Basic examines each Catch statement within the Try...Catch...Finally until it finds one whose condition matches that error. If one is found, control transfers to the first line of code in the Catch block. If no matching Catch statement is found, the search proceeds to the Catch statements of the outer Try...Catch...Finally block that contains the block in which the exception occurred. This process continues through the entire stack until a matching Catch block is found in the current procedure. If none is found, an error is produced.

12 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Introduction VB.NET The code in the Finally section always executes last, just before the error-handling block loses scope, regardless of whether the code in the Catch blocks has executed. Place cleanup code, such as that for closing files and releasing objects, in the Finally section. Prepared by Hoeung Rathsokha

Error Filtering in the Catch Block Catch blocks allow three options for specific error filtering. In one, errors are filtered based on the class of the exception (in this case ClassLoadException), as shown in the following code: Try ' "Try" block. Catch e as ClassLoadException ' "Catch" block. Finally ' "Finally" block. End Try

If a ClassLoadException error occurs, the code within the specified Catch block is executed. In the second error-filtering option, the Catch section can filter on any conditional expression. One common use of this form of Catch filter is to test for specific error numbers, as shown in the following code: Try ' "Try" block. Catch When ErrNum = 5 'Type mismatch. ' "Catch" block. Finally ' "Finally" block. End Try

When Visual Basic finds the matching error handler, it executes the code within that handler, and then passes control to the Finally block. Note When trying to find a Catch block to handle an exception, each block's handler is evaluated until a match is found. Since these handlers can be calls to functions, unexpected side effects may result; for example, such a call might change a public variable that is then used in the code of a different Catch block that ends up handling the exception.

As a third alternative, you can combine options one and two and use both for exception handling. Your Catch statements should move from most specific to least specific. A Catch block by itself will catch all exceptions derived from System.Exception, and therefore should always be placed as the last block before Finally.

Research and Academic Affairs

Batchelor Course 13


Visual Basic .NET

Structured Exception Handler Example The following example shows another simple error handler based on the Try...Catch...Finally statement: Function GetStringsFromFile(ByVal FileName As String) As Collection Dim Strings As New Collection Dim Stream As System.IO.StreamReader = System.IO.File.OpenText(FileName) 'Open the file. Try While True ' Loop terminates with an EndOfStreamException ' error when end of stream is reached. Strings.Add(Stream.ReadLine()) End While Catch eos As System.IO.EndOfStreamException ' No action is necessary; end of stream has been reached. Catch IOExcep As System.IO.IOException ' Some kind of error occurred. Report error and clear collection. MsgBox(IOExcep.Message) Strings = Nothing Finally Stream.Close() ' Close the file. End Try Return Strings End Function

The Finally block is always run, regardless of any actions occurring in preceding Catch blocks. You cannot use Resume or Resume Next in structured exception handling. Note Any exception other than the IOException class or the EndOfStreamException class is propagated back to the caller unhandled.

14 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Introduction VB.NET

Prepared by Hoeung Rathsokha

The Control Flow Test Structures Loop Structures Nested Control Structures

Test Structures An application need to built-in capability to test conditions and take a different course of action depending on the outcome of the test. In Visual Basic provides three such decision structures: 1

If…Then: test the condition specified; if it‘s True, the program executes the statement(s) that follow. If condition Then Statement Or execute multiple statements by separating them with colons. If condition Then Statement: Statement: Statement

2

3

If…Then…Else: Execute one block of statements if the condition is True and another block of statements if the condition is False. If condition1 Then Statements ElseIf condition2 Then Statements :::::::::::::::::::::::::::: Else Statements End If Select Case: The advantage of the select case statement over multiple If…Then…Else/ElseIf statements is that it makes the code easier to read and maintain. The select case structure tests a single expression, which is evaluated once at the top of the structure. The result of the test is then compared with several values, and if it matches one of them, the corresponding block of statements is executed. Select Case expression Case value1 Statements Case value2 Statements :::::::::::::::::::::: Case Else StatementsN End Select

Ex. Dim Msg As String Select Case Now.DayOfWeek Case DayOfWeek.Monday Msg=‖Have a nice week‖ Case DayOfWeek.Friday Msg=‖Have a nice weekend‖ Case Else Msg=‖Welcome Back!‖ Research and Academic Affairs

Batchelor Course 15


Visual Basic .NET End Select Msgbox (Msg)

Loop Structures Loop structure allow you to execute one or more lines of code repetitively. Many tasks consist of trivial operations that must be operated over and over again, and looping tructures are an important part of any programming language. VB supports the following loop structures: 1 For…Next: is one of the oldest loop structures in programming languages. The For..loop uses a variable(Counter) that increases or decreases in value during each repetition of the loop.

For Counter = Start To End [Step increment] Statements Next Ex. Calculate average Dim Data() As type = {10.50, 11.60, 12.70, 13.80, 14.90} Dim Counter As Integer, Total As Double For Counter = 0 To Data.GetUpperBound(0) Total += Data(Counter) Next Console.WriteLine (Total / Data.Length) 2 Do…Loop: Executes a block of a statements for as long as a condition is true. The expression is evaluated again and, if it‘s True, the statement are repeated. o

To execute a block of statements while a condition is True:

Do While Condition ’ execute when then condition is True. Statements Loop ‘until False. o

To execute a block of statements until the condition becomes True:

Do Until Condition Statements Loop

’ execute when then condition is False. ‘until True.

3 While…End While loop executes a block of a statements for as long as a condition is true.

While Condition Statements End While

’ execute if condition is True. ‘End while if condition is False.

Note: The End While statement replaces the Wend Statement of VB6.

Nest Control Structures In Visual Basic, you can place, or nest, control structures inside other control structures (Ex. If..Then within a For…Next loop). When you nest control structures, you must make sure that they open and close within the same structure.

16 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Prepared by Hoeung Rathsokha

Introduction VB.NET

Principles of Object-Oriented Programming It is often said that there are four main concepts in the area of object-oriented programming: Abstraction Encapsulation Inheritance Polymorphism Encapsulation and abstraction are "abstract" concepts providing motivation for object-oriented programming. Inheritance and polymorphism are concepts that are directly implemented in VB .NET programming.

Abstraction An abstraction is a view of an entity that includes only those aspects that are relevant for a particular situation. For instance, suppose that we want to create a software component that provides services for keeping a company's employee information. For this purpose, we begin by making a list of the items relevant to our entity (an employee of the company). Some of these items are: FullName Address EmployeeID Salary IncSalary DecSalary In short, we have abstracted the concept of an employee—we have included only those properties and methods of employees that are relevant to our needs. Once the abstraction is complete, we can proceed to encapsulate these properties and methods within a software component.

Interfaces We have seen that interfaces can be defined in class modules. VB .NET also supports an additional method of defining an interface, using the Interface keyword. The following example defines the IShape interface: Public Interface IShape Sub Draw() Sub Rotate(ByVal sngDegrees As Single) Sub Translate(ByVal x As Integer, ByVal y As Integer) Sub Reflect(ByVal iSlope As Integer, ByVal iIntercept As Integer) End Interface Note that we cannot implement any of the members of an interface defined using the Interface keyword, that is, not within the module in which the interface is defined. However, we can implement Public Class CRectangle ' Implement the interface IShape Implements IShape Public Overridable Sub Draw() Implements IShape.Draw ' code to implement Draw for rectangles End Sub Public Overridable Sub Spin() Implements IShape.Rotate ' code to implement Rotate for rectangles End Sub End Class

Encapsulation The idea of encapsulation is to contain (i.e., encapsulate) the properties and methods of an abstraction, and expose only those portions that are absolutely necessary. Each property and method of an abstraction is called a member of the abstraction. The set of exposed members of an abstraction is referred to collectively as the public interface (or just interface) of the abstraction (or of the software component that encapsulates the abstraction).

Research and Academic Affairs

Batchelor Course 17


Visual Basic .NET Encapsulation serves three useful purposes:  It permits the protection of these properties and methods from any outside tampering.  It allows the inclusion of validation code to help catch errors in the use of the public interface. For instance, it permits us to prevent the client of the employee software component from setting an employee's salary to a negative number.

It frees the user from having to know the details of how the properties and methods are implemented.

Inheritance The Inherits statement is used to declare a new class, called a derived class, based on an existing class, known as a base class. Derived classes inherit, and can extend, the properties, methods, events, fields, and constants defined in the base class. The following section describes some of the rules for inheritance, and the modifiers you can use to change the way classes inherit or are inherited: 

All classes are inheritable by default unless marked with the NotInheritable keyword. Classes can inherit from other classes in your project or from classes in other assemblies that your project references. Unlike languages that permit multiple inheritance, Visual Basic .NET permits only single inheritance in classes; that is, derived classes can have only one base class. Although multiple inheritances are not allowed in classes, classes can implement multiple interfaces, which can effectively accomplish the same ends. To prevent exposing restricted items in a base class, the access type of a derived class must be equal to or more restrictive than its base class. For example, a Public class cannot inherit a Friend or a Private class, and a Friend class cannot inherit a Private class.

Polymorphism The term polymorphism means having or passing through many different forms. In the .NET Framework, polymorphism is tied directly to inheritance. Again, let us consider our Employee example. The function IncSalary is defined in three classes: the base class CEmployee and the derived classes CExecutive and CSecretary. Thus, the IncSalary function takes on three forms. This is polymorphism, VB .NET style.

Classes Generally speaking, a class is a software component that defines and implements one or more interfaces. (Strictly speaking, a class need not implement all the members of an interface. We discuss this later when we talk about abstract members.) In different terms, a class combines data, functions, and types into a new type. Microsoft uses the term type to include classes.

1. Class Members In VB .NET, class modules can contain the following types of members: Data members (Member variables, Member constant) This includes member variables (also called fields) and constants. Event members: Events are procedures that are called automatically by the Common Language Runtime in response to some action that occurs, such as an object being created, a button being clicked, a piece of data being changed, or an object going out of scope. Function members: This refers to both functions and subroutines. A function member is also called a method. Property members: A property member is implemented as a Private member variable together with a special type of VB function that incorporates both accessor functions of the property.

2. Properties Properties are members that can be implemented in two different ways. In its simplest implementation, a property is just a public variable, as in: Public Class CStudent Public Age As Integer End Class

18 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Prepared by Hoeung Rathsokha

Introduction VB.NET

The problem with this implementation of the Age property is that it violates the principle of encapsulation; anyone who has access to a CStudent object can set its Age property to any Integer value, even negative integers, which are not valid ages. In short, there is no opportunity for data validation. (Moreover, this implementation of a property does not permit its inclusion in the public interface of the class, as we have defined that term.) The "proper" object-oriented way to implement a property is to use a Private data member along with a special pair of function members. The Private data member holds the property value; the pair of function members, called accessors, are used to get and set the property value. This promotes data encapsulation, since we can restrict access to the property via code in the accessor functions, which can contain code to validate the data. The following code implements the Age property. Private miAge As Integer Property Age() As Integer Get Age = miAge End Get Set(ByVal Value As Integer) ' Some validation If Value < 0 Then MsgBox("Age cannot be negative.") Else miAge = Value End If End Set End Property As you can see from the previous code, VB has a special syntax for defining the property accessors. Note the Value parameter that provides access to the incoming value. Thus, if we write: Dim Age As New CStudent Age.Age = 20 then VB passes the value 20 into the Property procedure in the Value argument.

3. Class Constructors When an object of a particular class is created, the compiler calls a special function called the class' constructor or instance constructor. Constructors can be used to initialize an object when necessary. (Constructors take the place of the Class_Initialize event in earlier versions of VB.) We can define constructors in a class module. However, if we choose not to define a constructor, VB uses a default constructor. For instance, the line: Dim Age As CStudent = New CStudent To define a custom constructor, we just define a subroutine named New within the class module. For instance, suppose we want to set the Name property to a specified value when a CStudent object is first created. Then we can add the following code to the CStudent class: ' Custom constructor Sub New(ByVal IAge As Integer) Me.miAge = IAge End Sub Now we can create a CStudent object and set its name as follows: Dim Age As CStudent = New CStudent(18) or Dim Age As New CStudent(18) Instead, to call a parameter less constructor, we must specifically add the constructor to the class module: ' Default constructor Sub New() ... End Sub

4. Finalize, Dispose, and Garbage Collection

Research and Academic Affairs

Batchelor Course 19


Visual Basic .NET In VB 6, a programmer can implement the Class_Terminate event to perform any clean up procedures before an object is destroyed. For instance, if an object held a reference to an open file, it might be important to close the file before destroying the object itself. In VB .NET, the Terminate event no longer exists, and things are handled quite differently. To understand the issues involved, we must first discuss garbage collection. When the garbage collector determines that an object is no longer needed (which it does, for instance, when the running program no longer holds a reference to the object), it automatically runs a special destructor method called Finalize. However, it is important to understand that, unlike with the Class_Terminate event, we have no way to determine exactly when the garbage collector will call the Finalize method. We can only be sure that it will be called at some time after the last reference to the object is released. Any delay is due to the fact that the .NET Framework uses a system called reference-tracing garbage collection, which periodically releases unused resources. Finalize is a Protected method. That is, it can be called from a class and its derived classes, but it is not callable from outside the class, including by clients of the class. (In fact, since the Finalize destructor is automatically called by the garbage collector, a class should never call its own Finalize method directly.) If a class' Finalize method is present, then it should explicitly call its base class' Finalize method as well. Hence, the general syntax and format of the Finalize method is: Protected Overrides Sub Finalize() ' Cleanup code goes here MyBase.Finalize() End Sub The benefits of garbage collection are that it is automatic and it ensures that unused resources are always released without any specific interaction on the part of the programmer. However, it has the disadvantages that garbage collection cannot be initiated directly by application code and some resources may remain in use longer than necessary. Thus, in simple terms, we cannot destroy objects on cue. We should note that not all resources are managed by the Common Language Runtime. These resources, such as Windows handles and database connections, are thus not subject to garbage collection without specifically including code to release the resources within the Finalize method. But, as we have seen, this approach does not allow us or clients of our class to release resources on demand. For this purpose, the Base Class Library defines a second destructor called Dispose. Its general syntax and usage is: Class classname Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose ' cleanup code goes here ' call child objects' Dispose methods, if necessary, here End Sub ' Other class code End Class

5. MyBase The following list describes restrictions on using MyBase:   

 

MyBase refers to the immediate base class and its inherited members. It cannot be used to access Private members in the class. MyBase is a keyword, not a real object. MyBase cannot be assigned to a variable, passed to procedures, or used in an Is comparison. The method that MyBase qualifies does not need to be defined in the immediate base class; it may instead be defined in an indirectly inherited base class. In order for a reference qualified by MyBase to compile correctly, some base class must contain a method matching the name and types of parameters appearing in the call. You cannot use MyBase to call MustOverride base class methods. MyBase cannot be used to qualify itself. Therefore, the following code is illegal: MyBase.MyBase.BtnOK_Click()

' Syntax error.

MyBase cannot be used in modules.

20 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Prepared by Hoeung Rathsokha Introduction VB.NET  MyBase cannot be used to access base class members that are marked as Friend if the base class is in a different assembly. Notice:

There are five allowed modifiers or accessibility of a declared element is the ability to use it, that is, the permission for code to read it or write to it. 1. Public The Public keyword in the Dim statement declares elements to be accessible from anywhere within the same project, from other projects that reference the project, and from an assembly built from the project. The following code shows a sample Public declaration: Public Class ClassForEverybody

You can use Public only at module, namespace, or file level. This means you can declare a public element in a source file or inside a module, class, or structure, but not within a procedure. 2. Protected The Protected keyword in the Dim statement declares elements to be accessible only from within the same class, or from a class derived from this class. The following code shows a sample Protected declaration: Protected Class ClassForMyHeirs

You can use Protected only at class level, and only when declaring a member of a class. 3. Friend The Friend keyword in the Dim statement declares elements to be accessible from within the same project, but not from outside the project. The following code shows a sample Friend declaration: Friend StringForThisProject As String

You can use Friend only at module, namespace, or file level. This means you can declare a friend element in a source file or inside a module, class, or structure, but not within a procedure. 4. Protected Friend The Protected and Friend keywords together in the Dim statement declare elements to be accessible either from derived classes or from within the same project, or both. The following code shows a sample Protected Friend declaration: Protected Friend StringForProjectAndHeirs As String

You can use Protected Friend only at class level, and only when declaring a member of a class. 5. Private The Private keyword in the Dim statement declares elements to be accessible only from within the same module, class, or structure. The following code shows a sample Private declaration: Private NumberForMeOnly As Integer

You can use Private only at module, namespace, or file level. This means you can declare a private element in a source file or inside a module, class, or structure, but not within a procedure.

Research and Academic Affairs

Batchelor Course 21


Visual Basic .NET

Writing and Using Procedures Subroutine Functions

Structure of a Visual Basic Program A Visual Basic program has standard building blocks. Visual Basic code is stored in project modules. Projects are composed of files, which are compiled into applications. When you start a project and open the code editor, you see some code already in place and in the correct order. Any code that you write should follow this sequence: 1. Option statements 2. Imports statements 3. The Main procedure 4. Class, Module, and Namespace, if applicable, statements In addition, a program may contain conditional compilation statements. These can be placed anywhere in the module. Many programmers prefer to put them at the end. If you enter statements in a different order, compilation errors may result.

Option Statements Option statements establish ground rules for subsequent code, helping prevent syntax and logic errors. The Option Explicit statement ensures that all variables are declared and spelled correctly, which cuts back on time spent debugging later. The Option Strict statement helps prevent logic errors and data loss that can occur when you work between variables of different types. The Option Compare statement specifies the way strings are compared to each other, either by their Binary or Text arrangement.

Imports Statements Imports statements allow you to name classes and other types defined within the imported namespace without having to qualify them.

Main Procedure The Main procedure is the "starting point" for your application — the first procedure that is accessed when you run your code. Main is where you would put the code that needs to be accessed first. In Main, you can determine which form is loaded first when the program is started, find out if a copy of your application is already running on the system, establish a set of variables for your application, or open a database that the application requires. There are four varieties of Main: 

Sub Main()



Sub Main(ByVal CmdArgs() As String)



Function Main() As Integer



Function Main(ByVal CmdArgs() As String) As Integer

The most common variety of this procedure is Sub Main( ). 22 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Prepared by Hoeung Rathsokha

Introduction VB.NET

Class, Module, and Namespace Statements Classes and modules make up most of the code in your source file. They contain most of the code you write — mainly Sub, Function, Method and Event statements — along with variable declarations and other code needed to make your application run.

Conditional Compilation Statements Conditional compilation statements can appear anywhere within the module. They are set to execute if certain conditions are met during run time. You can also use them for debugging your application, since conditional code runs in debugging mode only.

Subroutines A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements. Each time the procedure is called, its statements are executed, starting with the first executable statement after the Sub statement and ending with the first End Sub, Exit Sub, or Return statement encountered. A Sub procedure performs actions but does not return a value. It can take arguments, such as constants, variables, or expressions that are passed to it by the calling code. The syntax for declaring a Sub procedure is as follows: [accessibility] Sub subname[(argumentlist)] ' Statements of the Sub procedure go here. End Sub e.g. ByVal Task As String Sub TellOperator(ByVal Task As String) Dim Stamp As Date ' Stamp is local to TellOperator. Stamp = TimeOfDay()' Get current time for time stamp. MessageBox.Show("Starting " & Task & " at " & CStr(Stamp)) End Sub 'A typical call to TellOperator is as follows: Call TellOperator("file update") - The accessibility can be Public, Protected, Friend, Protected Friend, or Private. - Argumentlist: You declare each argument for a procedure the same way you declare a variable, specifying the argument name and data type. Syntax: ByVal|ByRef argumentname As datatype eg ByVal Task As String Or ByRef Task As String If the argument is optional, you must also supply a default value in its declaration, as follows: Optional [ByVal|ByRef] argumentname As datatype = defaultvalue e.g. Optional ByVal Task As String = "file update" Or Optional ByRef Task As String = "file update"

Note: Optional :Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used.

ByVal : Optional. Indicates that the argument is passed by value. ByVal is the default in Visual Basic. Research and Academic Affairs

Batchelor Course 23


Visual Basic .NET

ByRef : Optional. Indicates that the argument is passed by reference Functions A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. Each time the procedure is called, its statements are executed, starting with the first executable statement after the Function statement and ending with the first End Function, Exit Function, or Return statement encountered. A Function procedure is similar to a Sub procedure, but it also returns a value to the calling program. A Function procedure can take arguments passed to it by the calling code, such as constants, variables, or expressions. The syntax for declaring a Function procedure is as follows: [accessibility] Function functionname[(argumentlist)] As datatype ' Statements of the Function procedure. End Function The accessibility can be Public, Protected, Friend, Protected Friend, or Private. You can define Function procedures in modules, classes, and structures. They are Public by default, which means you can call them from anywhere in your application. You declare each argument the same as you do for a Sub procedure.

Return Values The value a Function procedure sends back to the calling program is called its return value. The function returns the value in one of two ways: 

It assigns a value to its own function name in one or more statements of the procedure. Control is not returned to the calling program until an Exit Function or End Function statement is executed, as in the following example: Function functionname[(argumentlist)] As datatype ' ... functionname = expression 'Control remains within the function. ' ... End Function



It uses the Return statement to specify the return value, and returns control immediately to the calling program, as in the following example:

Function functionname[(argumentlist)] As datatype ' ... Return expression 'Control is returned immediately. ' ... End Function Example: 'The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, given the values for the other two sides: po

te

Side2

Hy

nu

se

?

Side1

Function Hypotenuse(ByVal Side1 As Single, ByVal Side2 As Single) As Single Return Math.Sqrt((Side1 ^ 2) + (Side2 ^ 2))

24 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Prepared by Hoeung Rathsokha

Introduction VB.NET

End Function

Property Statement Declares the name of a property, and the property procedures used to store and retrieve the value of the property. Keyword Property ProName([ ByVal parameter list ]) [ As typename ] Get [ block ] End Get Set(ByVal value As typename ) [ block ] End Set End Property Keyword: [ Default ] [ Public | Private | Protected | Friend | Protected Friend ][[ ReadOnly | WriteOnly ][ Overloads | Overrides ] [ Overridable | NotOverridable ] | MustOverride | Shadows | Shared ]

Default Optional. Declares a default property. Default properties must accept parameters and can be set and retrieved without specifying the property name. Overloads Optional. Indicates that this property overloads one or more properties defined with the same name in a base class. The argument list in this declaration must be different from the argument list of every overloaded property. The lists must differ in the number of arguments, their data types, or both. This allows the compiler to distinguish which version to use. 'The Overloads keyword is Optional. Overloads Function min(ByVal a As Double, ByVal b As Double) As Double Return IIf(a < b, a, b) End Function Overloads Function min(ByVal a As String, ByVal b As String) As String Return IIf(a < b, a, b) End Function Overloads Function min(ByVal a As Date, ByVal b As Date) As Date Return IIf(a < b, a, b) End Function 'Call. MsgBox(min(2, 5)) MsgBox(min("a", "A")) MsgBox(min("January,05,1996", "January,06,1996")) 'or MsgBox(min(#1/5/1996#, #1/6/1996#))

You do not have to use the Overloads keyword when you are defining multiple overloaded properties in the same class. However, if you use Overloads in one of the declarations, you must use it in all of them. You cannot specify both Overloads and Shadows in the same property declaration. Overrides Optional. Indicates that this property overrides an identically named property in a base class. The number and data types of the arguments, and the data type of the return value, must exactly match those of the base class property. Overridable Optional. Indicates that this property can be overridden by an identically named property in a derived class. NotOverridable Research and Academic Affairs

Batchelor Course 25


Visual Basic .NET Optional. Indicates that this property cannot be overridden in a derived class. Properties are NotOverridable by default but you cannot specify the NotOverridable modifier with properties or methods that do not override another member. MustOverride Optional. Indicates that this property is not implemented in this class, and must be implemented in a derived class for that class to be creatable. Shadows Optional. Indicates that this property shadows an identically named programming element, or set of overloaded elements, in a base class. You can shadow any kind of declared element with any other kind. If you shadow a property with another property, the arguments and the return type do not have to match those in the base class property. A shadowed element is unavailable in the derived class that shadows it. Note You cannot specify both Overloads and Shadows in the same property declaration. Example: Class A Public Sub F() Console.WriteLine("A.F") End Sub Public Overridable Sub G() Console.WriteLine("A.G") End Sub End Class Class B Inherits A Public Shadows Sub F() Console.WriteLine("B.F") End Sub Public Overrides Sub G() Console.WriteLine("B.G") End Sub End Class Module Test Sub Main() Dim b As New B() Dim a As A = b a.F() b.F() a.G() b.G() MessageBox.Show("Pause Screen") End Sub End Module

Shared Optional. Indicates that this is a shared property. This means it is not associated with a specific instance of a class or structure. You can call a shared property by qualifying it either with the class or structure name, or with the variable name of a specific instance of the class or structure. ReadOnly Optional. Indicates that a properties value can be retrieved, but it cannot be the modified. ReadOnly properties contain Get blocks but lack Set blocks. WriteOnly Optional. Indicates that a property can be the target of assignment but its value cannot be retrieved. WriteOnly properties contain Set blocks but lack Get blocks. Get Starts a Get property procedure used to return the value of a property. Get blocks are required unless the property is marked WriteOnly. End Get 26 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Introduction VB.NET

Prepared by Hoeung Rathsokha Terminates a Get property procedure. Set

Starts a Set property procedure used to set the value of a property. Set blocks are required unless the property is marked ReadOnly. The new value of a property is passed to the Set property procedure in a parameter named value when the value of the property changes End Set Terminates a Set property procedure. End Property Terminates a Property definition. The declaration of the property determines what the user can do with that property: 

If the ReadOnly modifier is used, the property is known as a "Read-only property" and must only have a Get…End Get block. Therefore, the user is only able to retrieve the value of the property. An error will be raised if the user attempts to assign a value to that property.



If the WriteOnly modifier is used, the property is known as a "Write-only property" and must only have a Set…End Set block. This allows the user to store a value to the property. An error will be raised if the user attempts to refer to the property, except in the assignment of a value to that property.



If neither the ReadOnly nor the WriteOnly modifier is used, the property must have both a Set…End Set and a Get…End Get block. The property is said to be a read-write property.

Example The following example declares a property in a class. Class Class1 ' Define a local variable to store the property value. Private PropertyValues As String() ' Define the default property. Default Public Property Prop1(ByVal Index As Integer) As String Get Return PropertyValues(Index) End Get Set(ByVal Value As String) If PropertyValues Is Nothing Then ' The array contains Nothing when first accessed. ReDim PropertyValues(0) Else ' Re-dimension the array to hold the new element. ReDim Preserve PropertyValues(UBound(PropertyValues)+1) End If PropertyValues(Index) = Value End Set End Property End Class Sub UsePro() Dim C As New Class1() ' The first two lines of code access a property the standard way. C.Prop1(0) = "Value One" ' Property assignment. MessageBox.Show(C.Prop1(0)) ' Property retrieval. ' The following two lines of code use default property syntax. C(1) = "Value Two" MessageBox.Show(C(1)) End Sub

' Property assignment. ' Property retrieval.

Share: The Shared(C# is Static) modifier indicates the method does not operate on a specific instance of a type and may be invoked directly from a type rather than through a particular instance of a type. It is valid, however, to use an instance to qualify a Shared method. Research and Academic Affairs

Batchelor Course 27


Visual Basic .NET Class Test Private x As Integer Private Shared y As Integer Sub F() x = 1 ' Ok, same as Me.x = 1. y = 1 ' Ok, same as Test.y = 1. End Sub Shared Sub G() x = 1 ' Error, cannot access Me.x. y = 1 ' Ok, same as Test.y = 1. End Sub Shared Sub Main() Dim t As New Test() t.x = 1 ' Ok. t.y = 1 ' Ok. Test.x = 1 ' Error, cannot access instance member through type. Test.y = 1 ' Ok. End Sub End Class

28 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Introduction VB.NET

Prepared by Hoeung Rathsokha

Basic Windows Controls The TextBox Control The TextBox control in Visual Basic 6.0 is replaced by the Windows Forms TextBox control in Visual Basic .NET. The names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior. Links are provided as necessary to topics explaining differences in behavior. Where there is no direct equivalent in Visual Basic .NET, links are provided to topics that present alternatives.

Properties Visual Basic 6.0 Alignment 0 - Left Justify 1 - Right Justify 2 - Center BackColor BorderStyle 0 – None 1 – Fixed Single CausesValidation Container DataChanged DataField DataFormat DataMember DataSource Enabled Font FontBold FontItalic FontName FontSize FontStrikethru FontUnderline ForeColor Height, Width HideSelection HWnd Index

Left Locked MaxLength

MousePointer MultiLine Name Research and Academic Affairs

Visual Basic .NET Equivalent TextAlign HorizontalAlignment.Left HorizontalAlignment.Right HorizontalAlignment.Center BackColor BorderStyle BorderStyle.None BorderStyle.FixedSingle CausesValidation Parent No equivalent.

Enabled Font Note Fonts are handled differently in Visual Basic .NET.

ForeColor Size (Height, Width) HideSelection Handle No equivalent. You can duplicate the functionality using another common property such as the TabIndex or Tag property with that share the same events. Left ReadOnly MaxLength Note In Visual Basic 6.0 it was not possible to programmatically set the Text property to a length greater than the MaxLength value; in Visual Basic .NET this is now possible. Cursor MultiLine Name Batchelor Course 29


Visual Basic .NET Parent PasswordChar RightToLeft True False ScrollBars 0 – None 1 – Horizontal 2 – Vertical 3 – Both SelLength SelStart SelText TabIndex TabStop Tag Text ToolTipText

Top Visible

FindForm method PasswordChar RightToLeft RightToLeft.Yes RightToLeft.No ScrollBars ScrollBars.None ScrollBars.Horizontal ScrollBars.Vertical ScrollBars.Both SelectionLength SelectionStart SelectedText TabIndex TabStop Tag Text ToolTip component For more information, see ToolTip control (it is used to control the ToolTips for all controls on a form). Top Visible

Methods Visual Basic 6.0 Drag Refresh SetFocus ZOrder 0–vbBringToFront 1 - vbSendToBack

Visual Basic .NET Equivalent No equivalent. For more information, see Drag and Drop Changes in Visual Basic .NET. Refresh Focus BringToFront() or SendToBack() functions BringToFront() SendToBack()

Events Visual Basic 6.0 Change Click DblClick DragDrop DragOver GotFocus KeyDown KeyPress KeyUp LostFocus MouseDown MouseMove MouseUp Validate

Visual Basic .NET Equivalent TextChanged No equivalent. Use MouseUp as an alternative. DoubleClick No equivalent. For more information, see Drag and Drop Changes in Visual Basic .NET. Enter KeyDown KeyPress KeyUp Leave MouseDown MouseMove MouseUp Validating

30 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Prepared by Hoeung Rathsokha

Introduction VB.NET

What’s new in VB.NET vs. VB6 (No equivalent) Copy Method Copies the current selection in the text box to the Clipboard Or Clipboard.SetDataObject(textBox1.SelectedText) Paste Method Replaces the current selection in the text box with the contents of the Clipboard. Or Dim iData As IDataObject = Clipboard.GetDataObject() Cut Method Moves the current selection in the text box to the Clipboard Clear Method Clears all text from the text box control ClearUndo Method Clears information about the most recent operation from the undo buffer of the text box. CanUndo Property (Boolean) Gets a value indicating whether the user can undo the previous operation in a text box control Undo Method Undoes the last edit operation in the text box e.g.

If TextBox1.CanUndo = True Then TextBox1.Undo() ' Undo the last operation. TextBox1.ClearUndo() ' Clear the undo buffer. End If

Lines Property

Gets or sets the lines of text in a text box control. 'Create a string array and store the contents of the Lines property

ResetText Method

Dim tempArray() as String tempArray = textBox1.Lines Resets the Text property to its default value

ListBox control The ListBox control enables you to display a list of items to the user that the user can select by clicking. A ListBox control can provide single or multiple selections using the SelectionMode property. The ListBox also provides the MultiColumn property to enable the display of items in columns instead of a straight vertical list of items. This allows the control to display more visible items and prevents the need for the user to scroll to an item. o The SelectionMode property enables you to determine how many items in the ListBox a user can select at one time and how the user can make multiple-selections. When the SelectionMode property is set to SelectionMode.MultiExtended, pressing SHIFT and clicking the mouse or pressing SHIFT and one of the arrow keys (UP ARROW, DOWN ARROW, LEFT ARROW, and RIGHT ARROW) extends the selection from the previously selected item to the current item. Pressing CTRL and clicking the mouse selects or deselects an item in the list. When the property is set to SelectionMode.MultiSimple, a mouse click or pressing the SPACEBAR selects or deselects an item in the list.

Member Description MultiExtended: Multiple items can be selected, and the user can use the SHIFT, CTRL, and arrow keys to make selections MultiSimple: Multiple items can be selected None: No items can be selected. Research and Academic Affairs

Batchelor Course 31


Visual Basic .NET One: Only one item can be selected o ClearSelected: Unselects all items in the List Box. ListBox1.ClearSelected()

o

Items: Gets or sets the item at the specified index within the collection.  Add Adds an item to the list of items for a List Box. ListBox1.Items.Add("aa")

 AddRange

Adds a group of items to the list of items for a List Box. Dim ar() As String = {"11", "22", "33", "44", "55"} ListBox1.Items.AddRange(ar)

 Clear  Insert

Removes all items from the collection. Inserts an item into the list box at the specified index. Dim obj() As Object = {"Visual", "Basic", ".NET", "version", "7"} Dim j As Integer For j = 0 To 4 ListBox1.Items.Insert(j, obj(j)) Next

 Remove

Removes the specified object from the collection. ListBox1.Items.Remove(ListBox1.SelectedItem)

 RemoveAt

Removes the item at the specified index within the collection. ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)

 Count Gets the number of items in the collection o FindString: Gets or sets the item at the specified index within the collection. Returns ListBox.NoMatches if no match is found  Finds the first item in the ListBox that exactly matches or starts with the specified string. Set to negative one (-1) to search from the beginning of the control Near match index = FindStringExact(String,startIndex) As Integer Exact Match index = FindString(String,startIndex) As Integer Dim ind As Integer ind = ListBox1.FindString("basic") If ind < 0 Then MsgBox("not found!") Else ListBox1.SelectedIndex = ind ListBox1.TopIndex = ind End If

CheckedListBox Control o

SetItemChecked: When a value of true is passed, this method sets the checked value of the item to Checked. A value of false will set the item to Unchecked.

o

SetItemCheckState: Sets the check state of the item at the specified index.

CheckedListBox1.SetItemChecked(3, True)

Indeterminate: The control is indeterminate. An indeterminate control generally has a shaded appearance e.g. CheckedListBox1.SetItemCheckState(3, CheckState.Indeterminate)

32 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Prepared by Hoeung Rathsokha

Introduction VB.NET

CheckedListBox1.SetItemCheckState(4, CheckState.Unchecked)

ComboBox Control o

A ComboBox displays an editing field combined with a ListBox, allowing the user to select from the list or to enter new text DropDownStuyle: Gets or sets a value specifying the style of the combo box.

 Simple The text portion is editable. The list portion is always visible.  DropDown The text portion is editable. The user must click the arrow button to display the list portion.  DropDownList The user cannot directly edit the text portion. The user must click the arrow button to display the list portion. o MaxDropDownItems: Gets or sets the maximum number of items to be shown in the drop-down portion of the ComboBox. The maximum number of items of in the dropdown portion. The minimum for this property is 1 and the maximum is 100. o DropDownWidth: Gets or sets the width of the of the drop-down portion of a combo box. The width, in pixels, of the drop-down box.

Common dialog Controls

OpenFileDialog Represents a common dialog box that displays the control that allows the user to open a file. ShowDialog: Runs a common dialog box with a default owner. DialogResult.OK if the user clicks OK in the dialog box; otherwise, DialogResult.Cancel .

With OpenFileDialog1 .InitialDirectory = "c:\" .Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" .FilterIndex = 2 '*.* .RestoreDirectory = True 'restores the current directory before closing .Multiselect = True

Research and Academic Affairs

Batchelor Course 33


Visual Basic .NET If .ShowDialog = DialogResult.Cancel Then Exit Sub 'MessageBox.Show(OpenFileDialog1.FileName) file name.

'Get|set containing the

Dim x() As String x =.FileNames 'Gets the file names of all selected files in the dialog box Dim a As String For Each a In x TextBox1.Text = TextBox1.Text & vbCrLf & a Next End With

SaveFileDialog Represents a common dialog box that allows the user to specify options for saving a file. This class cannot be inherited. Remarks This class allows you to open and overwrite an existing file or create a new file. Example The following example illustrates instantiating a SaveFileDialog, setting members, calling the dialog using ShowDialog , and opening the selected file. The example assumes a form with a button placed on it. Protected Sub button1_Click(sender As Object, e As System.EventArgs) Dim myStream As Stream Dim saveFileDialog1 As New SaveFileDialog() saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" saveFileDialog1.FilterIndex = 2 saveFileDialog1.RestoreDirectory = True If saveFileDialog1.ShowDialog() = DialogResult.OK Then myStream = saveFileDialog1.OpenFile() If Not (myStream Is Nothing) Then ' Code to write the stream goes here. myStream.Close() End If End If End Sub

PrintFileDialog Allows users to select a printer and choose which portions of the document to print. Remarks When you create an instance of PrintDialog, the read/write properties are set to initial values.

FontFileDialog Represents a common dialog box that displays a list of fonts that are currently installed on the system. Remarks The inherited member ShowDialog must be invoked to create this specific common dialog box. HookProc can be overridden to implement specific dialog box hook functionality. Example The following example uses ShowDialog to display a FontDialog. This code assumes that a Form has already been instantiated with a TextBox and button placed on it. It also 34 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Prepared by Hoeung Rathsokha Introduction VB.NET assumes the fontDialog1 has been instantiated. The Font contains the the size information but not the color information. Protected Sub button1_Click(sender As Object, e As System.EventArgs) fontDialog1.ShowColor = True If fontDialog1.ShowDialog() <> DialogResult.Cancel Then textBox1.Font = fontDialog1.Font textBox1.ForeColor = fontDialog1.Color End If End Sub 'button1_Click

ColorFileDialog Represents a common dialog box that displays available colors along with controls that allow the user to define custom colors. Example The following example illustrates the creation of new ColorDialog. This example assumes that the method is called from within an existing form, that has a TextBox and Button placed on it. Protected Sub button1_Click(sender As Object, e As System.EventArgs) Dim MyDialog As New ColorDialog() ' Keeps the user from selecting a custom color. MyDialog.AllowFullOpen = False ' Allows the user to get help. (The default is false.) MyDialog.ShowHelp = True ' Sets the initial color select to the current text color, ' so that if the user cancels out, the original color is restored. MyDialog.Color = textBox1.ForeColor MyDialog.ShowDialog() textBox1.ForeColor = MyDialog.Color End Sub 'button1_Click

ToolTip Represents a small rectangular pop-up window that displays a brief description of a control's purpose when the mouse hovers over the control. Public Properties Active Gets or sets a value indicating whether the ToolTip is currently active. AutomaticDelay Gets or sets the automatic delay for the ToolTip. AutoPopDelay Gets or sets the period of time the ToolTip remains visible if the mouse pointer is stationary within a control with specified ToolTip text. InitialDelay Gets or sets the time that passes before the ToolTip appears. ReshowDelay Gets or sets the length of time that must transpire before subsequent ToolTip windows appear as the mouse pointer moves from one control to another. ShowAlways Gets or sets a value indicating whether a ToolTip window is displayed even when its parent control is not active. Example The following example creates an instance of the ToolTip class and associates it with the Form the instance is created within. The code then initializes the delay properties AutoPopDelay, InitialDelay, and ReshowDelay. In addition the instance of the ToolTip class sets the ShowAlways property to true to enable ToolTip text to always be display regardless of whether the form is active. Finally, the example associates ToolTip text with two controls on a form, a Button and a CheckBox . This example assumes that the method defined in the example is located within a Form that contains a Button control named button1 and a CheckBox control named checkBox1 and that the method is called from the constructor of the Form. Research and Academic Affairs

Batchelor Course 35


Visual Basic .NET [Visual Basic] Private Sub CreateMyToolTip() ' Create the ToolTip and associate with the Form container. Dim toolTip1 As New ToolTip(Me.components) ' Set up the delays for the ToolTip. toolTip1.AutoPopDelay = 5000 toolTip1.InitialDelay = 1000 toolTip1.ReshowDelay = 500 ' Force the ToolTip text to be displayed whether or not the form is active. toolTip1.ShowAlways = True ' Set up the ToolTip text for the Button and Checkbox. toolTip1.SetToolTip(Me.Button1, "My button1") toolTip1.SetToolTip(Me.CheckBox1, "My checkBox1") End Sub

RichTextBox The RichTextBox control allows the user to enter and edit text while also providing more advanced formatting features than the standard TextBox control. Text can be assigned directly to the control, or can be loaded from a Rich Text Format (RTF) or plain text file. The text within the control can be assigned character and paragraph formatting. The RichTextBox control provides a number of properties you can use to apply formatting to any portion of text within the control. To change the formatting of text, it must first be selected. Only selected text can be assigned character and paragraph formatting. Once a setting has been made to a selected section of text, all text entered after the selection is also formatted with the same settings until a setting change is made or a different section of the control's document is selected. The SelectionFont property enables you to make text bold or italic. You can also use this property to change the size and typeface of the text. The SelectionColor property enables you to change the color of the text. To create bulleted lists you can use the SelectionBullet property. You can also adjust paragraph formatting by setting the SelectionIndent , SelectionRightIndent, and SelectionHangingIndent properties. The RichTextBox control provides methods that provide functionality for opening and saving files. The LoadFile method enables you to load an existing RTF or ASCII text file into the control. You can also load data from an already opened data stream. The SaveFile enables you to save a file to RTF or ASCII text. Similar to the LoadFile method, you can also use the SaveFile method to save to an open data stream. The RichTextBox control also provides features for finding strings of text. The Find method is overloaded to find both strings of text as well as specific characters within the text of the control. You can also initialize the RichTextBox control to data stored in memory. For example, you can initialize the Rtf property to a string that contains the text to display, including the RTF codes that determine how the text should be formatted. If the text within the control contains links, such as a link to a Web site, you can use the DetectUrls property to display the link appropriately in the control's text. You can then handle the LinkClicked event to perform the tasks associated with the link. The SelectionProtected property enables you to protect text within the control from manipulation by the user. With protected text in your control, you can handle the Protected event to determine when the user has attempted to modify protected text to either alert the user that the text is protected or to provide the user with a standard form of manipulating the protected text.

Public Properties Rtf SelectedRtf

Gets or sets the text of the RichTextBox control, including all Rich Text Format (RTF) codes. Gets or sets the currently selected Rich Text Format (RTF) formatted text in the control.

36 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Prepared by Hoeung Rathsokha Introduction VB.NET SelectedText Overridden. Gets or sets the selected text within the RichTextBox. SelectionLength Overridden. Gets or sets the number of characters selected in control. SelectionStart (inherited from TextBoxBase) Gets or sets the starting point of text selected in the text box. SelectionBullet SelectionFont SelectionAlignment DetectUrls

ZoomFactor

Gets or sets a value indicating whether the bullet style is applied to the current selection or insertion point. Gets or sets the font of the current text selection or insertion point. Gets or sets the alignment to apply to the current selection or insertion point. Gets or sets a value indicating whether or not the RichTextBox will automatically format a Uniform Resource Locator (URL) when it is typed into the control. Gets or sets the current zoom level of the RichTextBox.

Public Methods Clear

(inherited from TextBoxBase) Clears all text from the text box control.

Copy

(inherited from TextBoxBase) Copies the current selection in the text box to the Clipboard. Cut (inherited from TextBoxBase) Moves the current selection in the text box to the Clipboard. Paste Overloaded. Pastes the contents of the Clipboard into the control. Redo Reapplies the last operation that was undone in the control. Undo (inherited from TextBoxBase) Undoes the last edit operation in the text box. Focus (inherited from Control) Sets input focus to the control. Find Overloaded. Searches for text within the contents of the RichTextBox. LoadFile Overloaded. Loads the contents of a file into the RichTextBox control. SaveFile Overloaded. Saves the contents of the RichTextBox to a file. CreateGraphics (inherited from Control) Creates the Graphics object for the control. CreateObjRef (inherited from MarshalByRefObject) Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

Research and Academic Affairs

Batchelor Course 37


Visual Basic .NET

File Access In Visual Basic, there are three types of file access:  Sequential — For reading and writing text files in continuous blocks.  Random — For reading and writing text or binary files structured as fixed-length records.  Binary — For reading and writing arbitrarily structured files

Opens a file for input or output: Public Sub FileOpen( _ ByVal FileNumber As Integer, _ ByVal FileName As String, _ ByVal Mode As OpenMode, _ Optional ByVal Access As OpenAccess = OpenAccess.Default, _ Optional ByVal Share As OpenShare = OpenShare.Default, _ Optional ByVal RecordLength As Integer = -1) Where: FileNumber Required. Any valid file number. Use the FreeFile function to obtain the next available file number. In Range: 1 to 255 ―in VB6 from 1 to 511‖ Dim fileNumber As Integer

fileNumber = FreeFile() FileName Required. String expression that specifies a file name — may include directory or folder, and drive. Mode Required. Enum specifying the file mode: Append, Binary, Input, Output, Random. Access Optional. Keyword specifying the operations permitted on the open file: Read, Write, or ReadWrite. Defaults to ReadWrite. Share Optional. Enum specifying the operations restricted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write. Defaults to Lock Read Write. RecordLength Optional. Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered. The FileOpen Function lets you create and access files with one of three types of file access:

1. Sequential access (Input, Output, and Append modes) is used for writing text files, such as error logs and reports. The statements typically used when writing data to and reading it from files Writing data  Print, PrintLine: Writes display-formatted data to a sequential file.  Write, WriteLine: Writes data to a sequential file. Data written with Write is usually read from a file with Input. Public Sub Print | PrintLine | Write | WriteLine (ByVal FileNumber As Integer, _ ByVal ParamArray Output() As Object) 38 Prepared by Hoeung Rathsokha Ref: Mastering VB.net; VB .NET Language in a Nutshell; http://www.microsoft.com/net/


Prepared by Hoeung Rathsokha

Introduction VB.NET

Reading data  InputString: Returns String value containing characters from a file opened in Input or Binary mode. InputString(ByVal FileNumber As Integer, ByVal CharCount As Integer) As String  LineInput: Reads a single line from an open sequential file and assigns it to a String variable. Public Function LineInput(ByVal FileNumber As Integer) As String

2. Random access (Random mode) is used to read and write data to a file without closing it. Randomaccess files keep data in records, which makes it easy to locate information quickly. The statements typically used when writing data to and reading it from files Writing data  FilePut: Writes data from a variable to a disk file. Reading data  FileGet: Reads data from an open disk file into a variable.

3. Binary access (Binary mode) is used to read or write to any byte position in a file, such as storing or displaying a bitmap image. Reading (FileGet) and Writing (FilePut) data is similar to random access file.

Research and Academic Affairs

Batchelor Course 39


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.