• Aucun résultat trouvé

Apprentissage du langage Visual Basic

N/A
N/A
Protected

Academic year: 2021

Partager "Apprentissage du langage Visual Basic"

Copied!
133
0
0

Texte intégral

(1)

Programming in VB.NET

Rohit Birla

[email protected] [email protected]

(2)(3)

3

Preface

It gives me great pleasure in presenting this book. “Programming in VB.NET” is

written with several goals in mind. It is designed to cover all essential and basic

information you will need to start your programming in VB.NET.

I hope this book will help you to start your programming in .NET.

In spite of all efforts some errors might be there. I shall be grateful to the

readers if the same are brought to my notice. Suggestions and comments for

further improvements of the book will be gratefully acknowledged.

June 29, 2010

Rohit Birla

[email protected] [email protected]

(4)

4

About the Author:

Rohit Birla; is a student, currently perusing MCA. His area

of interest includes Operating System Development and

Windows Application Development.

He is also the author of

- Let’s make Linux together

- Program your Linux

(5)

5

Dedicate to

(6)

6

About the book:

This book is designed especially for .NET beginners. Some

of the main features include:

 A Totally programming approach

 Theory is kept to its minimum

 Every Topic is covered with Example

 Bundle of Assignments

 No Syntax Errors, Every code is shown as

Screen-Shot

Before you start .NET, I expect you are comfortable with

OOP concepts and VB Language.

(7)

7

Contents:

PREFACE ... 3

ABOUT THE AUTHOR: ... 4

ABOUT THE BOOK: ... 6

CONTENTS: ... 7

.NET HISTORY ... 14

.NETHISTORY ... 14

APPLICATIONS THAT CAN BE DEVELOPED UNDER .NET ... 14

VISUAL STUDIO INTEGRATED DEVELOPED ENVIRONMENT ... 14

WHY TO USE VSIDE ... 14

TYPES OF APPLICATIONS ... 15

SINGLE TIER APPLICATIONS: ... 15

TWO TIER APPLICATIONS: ... 15

 FAT CLIENT: ... 15

 FAT SERVER: ... 15

 DIVIDING BUSINESS SERVICES BETWEEN USER AND DATA SERVICES: ... 15

LIMITATIONS OF TWO TIER APPLICATIONS: ... 16

THREE TIER APPLICATIONS:... 16

N –TIER APPLICATIONS: ... 16

WHY TO USE .NET ... 17

ADVANTAGES OF USING .NETFRAMEWORK ... 17

.NET ARCHITECTURE ... 17

LAYER 1: ... 18

LAYER 2: ... 18

LAYER 3: ... 18

MANAGE CODE ... 18

GARBAGE COLLECTION PROCESS ... 18

NAMESPACES: ... 19

ASSEMBLY: ... 19

MANAGE CODE EXECUTION PROCESS ... 20

EXPLANATION: ... 20

FIRST VB.NET PROGRAM... 21

HELLO WORLD AGAIN!!! ... 21

SECOND VB.NET PROGRAM ... 23

(8)

8

USING IF-ELSE ... 25

USING CONDITIONAL OPERATOR ... 25

LOOPING ... 26

Assignment: ... 26

DEFINING ARRAYS & FOR-EACH LOOP ... 27

SUBROUTINE VS. FUNCTION ... 27

DEFINITION OF SUBROUTINE AND FUNCTION ... 28

MULTI DIMENSION ARRAYS ... 28

RETRIEVING LOWER AND UPPER BOUND ... 28

Assignment ... 28

USING SELECT-CASE ... 29

FUNCTION OVERLOADING ... 29

Assignment ... 30

DEFINING CLASSES ... 30

MAKING A SIMPLE CLASS ... 30

CREATING CONSTRUCTOR ... 31 OVERLOADING CONSTRUCTOR ... 32 DEFINING PROPERTIES ... 33 OPERATOR OVERLOADING ... 34 Assignment ... 34 INHERITANCE ... 35 CODE REUSABILITY ... 35 TYPES OF INHERITANCE ... 35 VARIABLE SCOPE ... 35 HOW TO INHERIT ... 35

RUN TIME POLYMORPHISM ... 37

OBJECT SLICING,RUN TIME BINDING,LATE BINDING... 37

EXAMPLE ... 37

MAIN1 ... 37

MAIN2 ... 38

RUN TIME POLYMORPHISM MAIN3 ... 38

Assignment: ... 39

ABSTRACT CLASSES ... 41

EXPLANATION: ... 41

EXAMPLE: ... 41

(9)

9

EXPLANATION: ... 42

ABSTRACT CLASS VS.INTERFACE ... 42

EXAMPLE1 ... 42

EXAMPLE2IMPLEMENTING MULTIPLE INTERFACES ... 43

EXAMPLE3INHERITING INTERFACES ... 44

NON INHERITABLE CLASS ... 45

EXAMPLE ... 45

ENUMERATION ... 45

OVERRIDING TOSTRING () FUNCTION ... 46

EXAMPLE: ... 46

UNDERSTANDING CONSOLE ... 47

CREATING NAMESPACE ... 47

COMMAND LINE ARGUMENTS ... 48

PASSING COMMAND LINE ARGUMENTS ... 48

Assignment ... 49

USING VB6.0 FILE HANDLING IN VB.NET ... 50

USING MICROSOFT.VISUALBASIC NAMESPACE ... 50

.NET FILE HANDLING ... 51

USING SYSTEM.IO NAMESPACE ... 51

SMALL-SMALL BIG-BIG FUNCTIONS ... 52

CREATING DIRECTORY ... 52

COPY ONE FILE TO ANOTHER ... 52

GETTING DRIVE INFORMATION ... 52

UNDERSTANDING SYSTEM.ENVIRONMENT ... 53

GETTING USER NAME ... 53

GETTING CURRENT DIRECTORY ... 53

GETTING SYSTEM DIRECTORY ... 53

GETTING FOLDER PATH ... 53

GETTING OPERATING SYSTEM VERSION ... 53

CHECKING WHETHER IT IS 64 BIT OS OR NOT ... 53

UNDERSTANDING MY.COMPUTER ... 54

GETTING GMT TIME ... 54

CHECKING VARIOUS KEYS LIKE CAPS LOCK, NUM LOCK, SHIFT ETC… ... 54

CHECKING WHETHER MOUSE IS LEFT HANDED OR RIGHT HANDED ... 54

GETTING COMPUTER NAME ... 54

CHECKING TOTAL PHYSICAL MEMORY ... 54

CHECKING TOTAL VIRTUAL MEMORY ... 54

(10)

10

CHECKING SCREEN INFORMATION, RESOLUTION ETC… ... 54

GETTING OS PLATFORM ... 54

GETTING CULTURE ... 54

FILE SYSTEM ... 54

Assignment ... 55

GENERATING RANDOM NUMBERS ... 56

USING SYSTEM.COLLECTIONS ... 56

STACK ... 56

QUEUE ... 57

USING SUBSTRING FUNCTION ... 58

Assignment ... 58 DATETIME FUNCTIONS ... 59 Assignment: ... 59 EXCEPTION HANDLING ... 60 TRY-CATCH ... 60 TRY –THROW –CATCH ... 60

TRY –THROW –MULTIPLE CATCH ... 61

EXCEPTION CLASS ... 62

USING EXCEPTION CLASS... 62

TRY –THROW –CATCH –FINALLY ... 63

NESTED TRY ... 64

NESTED –TRY EXAMPLE ... 64

EXAMPLES OF VARIOUS EXCEPTIONS ... 65

USER –DEFINED EXCEPTION ... 65

USER –DEFINED EXCEPTION EXAMPLE ... 66

Assignment ... 66

WINDOWS APPLICATIONS ... 67

A LOOK AT CONTROLS IN VB.NET ... 67

CREATING FIRST WINDOWS APPLICATION ... 68

SECOND WINDOWS APPLICATION ... 70

LIST OF CONTROLS; WE WILL BE LOOKING AT ... 71

LABEL ... 73 PROPERTIES WINDOW: ... 73 EVENTS: ... 73 TEXTBOX ... 74 PROPERTIES WINDOW: ... 74 EVENTS: ... 74 FORM... 75

(11)

11 PROPERTIES WINDOW: ... 75 EVENTS: ... 75 BUTTON ... 76 PROPERTIES WINDOW: ... 76 EVENTS: ... 76

A FUNNY APPLICATION – CONFUSION! ... 77

AGAIN CONFUSION!! ... 78 CHECKBOX ... 79 PROPERTIES WINDOW: ... 79 EVENTS: ... 79 EXAMPLE: ... 79 TRACKBAR ... 81 PROPERTIES WINDOW: ... 81 EVENTS: ... 81 EXAMPLE: ... 81 VSROLLBAR ... 82 EXAMPLE: ... 82 Assignment ... 82 TIMER ... 83 PROPERTY WINDOW: ... 83 EXAMPLE: ... 83 LINKLABEL ... 84 EXAMPLE: ... 84 PROGRESSBAR ... 85 EXAMPLE: ... 85 WEBBROWSER ... 86 EXAMPLE: ... 86 MASKEDTEXTBOX ... 87 RADIOBUTTON ... 88 EXAMPLE: ... 88 A BIG CONFUSION!!! ... 89 CONFUSION SOLVED ... 90 COMBOBOX ... 91 EXAMPLE: ... 91 STILL, CONFUSION!!! ... 92

(12)

12 CONFUSION SOLVED: ... 92 COLORDIALOG ... 93 EXAMPLE: ... 93 FONTDIALOG ... 94 EXAMPLE: ... 94 FOLDERBROWSERDIALOG ... 95 EXAMPLE: ... 95 OPENFILEDIALOG ... 96 EXAMPLE: ... 96 ADOBEPDF ... 97 EXAMPLE: ... 97 NUMERICUPDOWN ... 98 EXAMPLE: ... 98 MONTHCALENDAR ... 99 DATETIMEPICKER ... 99 EXAMPLE: ... 99 MESSAGEBOX ... 100 VARIANTS OF MESSAGEBOX: ... 100 INPUTBOX ... 100 VARIANTS OF INPUTBOX: ... 100 LISTBOX ... 101 EXAMPLE: ... 101

CONFIGURE LISTBOX FOR MULTIPLE SELECTIONS ... 102

CHECKLISTBOX ... 104 EXAMPLE: ... 104 MENUSTRIP ... 105 CONTEXTMENUSTRIP ... 107 ERRORPROVIDER: ... 108 RICHTEXTBOX ... 109 Assignment: ... 109 FLOWLAYOUT ... 110

FLOWLAYOUT EXAMPLE: ... 110

(13)

13

TABLELAYOUT EXAMPLE: ... 110

MEDIAPLAYER... 111 TOOLTIP ... 113 PICTUREBOX ... 114 STATUSSTRIP ... 114 EXAMPLE: ... 115 TOOLSTRIP ... 116

ADDING STANDARD ITEMS: ... 117

TABCONTROL ... 118

SOME HINTS: ... 118

PRINTING: ... 118

PRINTDIALOG AND PRINTFORM ... 119

ADDING CONTROLS AT RUNTIME ... 119

ANIMATION: ... 120

NOTE: ... 121

GRAPHICS: ... 122

DRAWING LINE AND RECTANGLE: ... 122

NOTIFYICON... 122

Assignment: ... 124

DATABASE CONNECTIVITY ... 125

ADO.NET ... 125

BASIC STEPS TO FOLLOW: ... 125

DISPLAYING ALL RECORDS AT A TIME USING DATA ADAPTER AND DATA SET ... 126

SEARCHING USING DATA ADAPTER AND DATA SET ... 127

READING ONE VALUE AT A TIME USING DATA ADAPTER AND DATA SET ... 128

READING ONE VALUE AT A TIME USING COMMAND AND DATA READER ... 129

SEARCHING USING COMMAND: ... 130

SEARCHING USING COMMAND AGAIN: ... 131

INSERTION INTO TABLE USING COMMAND: ... 132

DELETION USING COMMAND: ... 132

(14)

14

.NET History

.NET History

 .NET 1.0 2002  .NET 1.1 2003  .NET 2.0 2005  .NET 3.0 2007  .NET 3.5 2008  .NET 4.0 2010

.NET 2010 is the latest version of .NET. We will be using the same in our programs.

Applications that can be developed under .NET

 Console Applications  Windows Applications  Web Applications  Component Libraries  Windows Custom Control  Web Custom Control  Web Service

 Windows Service  And lots more…

Visual Studio Integrated Developed Environment

Why to use VS IDE

 Drag and Drop Design  IntelliSense features

 Syntax highlighting and auto syntax checking  Excellent debugging tools

 Integrated with Visual Source Safe  Easy Project Management

 When we install VS IDE, .NET Framework is automatically installed.

 We will be using VS 2010 in our programs.

(15)

15

Types of Applications

Single tier Applications:

A single executable file handles all functions relating to user, business and data service layer. Such an application also called monolithic application. Ex: Very early COBOL applications, console applications (DOS mode applications), In Dbase and FoxPro; user interface is with Database.

Two tier Applications:

It divides application in two parts - Client which implement user interface - Server which stores data

these both may be located separately or on a single machine. Ex: VB + SQL Server

 Fat Client:

Business services layer combine with user services layer. Client executes presentation logic and enforces business rules. Server stores data and process transactions. Fat client model is use when server is overloaded with transaction processing activities and not available to process business logic.

 Fat Server:

Business services layer combine with data services layer. As business services stored on server most of processing take place on server.

 Dividing business services between user and data services:

(16)

16

Limitations of two tier applications:

- Same Operating System required on both sides - Executable file should be on client side

- Dedicated LAN requirements for both the tiers

Three tier Applications:

The services layer resides separately, either on same or on different machine. The user interface interacts with business logic which validates data send by user interface and forwards to database if it confirm to requirement. The front-end only interact with business logic which in turn interacts with database.

n – Tier Applications:

An n tier architecture/ application use multiple server handling business services. This

architecture provides various advantages over other architectures. Ex: extensibility, maintainability and scalability. One of most important requirements of such application is the ability to interchange info across platform and to benefit from the functionality provided by other application. In other words, there should be increased interoperability and integration between various applications. A website may register its consumers and provides services to them; however it may not be capable of interacting with other websites that providing complementary services to customers. For performing such tasks;

(17)

17

Why to use .NET

Advantages of using .NET Framework

 Consistent Programming Model

 Rich Functionality (no need to go in low level details)  Easy development of web application

 Object Oriented Programming (Object is mother of all)  Multi Language Support

 Multi Device Support

 Automatic Memory Management (garbage collection)  DLL hell removed

 XML support

 Ease of deployment and configuration  Security

I left details of these points as an assignment to you.

(18)

18 .NET framework exists as a layer between .NET applications and underlying Operating System. The above figure shows components of .NET framework.

Layer 1:

Layer 1 Consists of web forms, windows forms and console applications that constitute to the presentation layer of an application. Web forms are used in web applications where as windows forms are used in windows based applications for providing interacting user interface. In addition, you can create character based console application that can be executed from command line.

Layer 2:

One of the most important features of .NET Framework class library is that it can be used in a consistent manner across multiple languages. This means, you can use same set of classes for

performing a specific task in VB.NET as well as in C++.NET. The .NET Framework class libraries contain namespaces which are contained within assemblies.

Layer 3:

The common language runtime provides functionality such as exception handling, security, debugging, and version control to any language that target it. This means that common language

runtime can host a variety of languages and offer a common set of tools across these languages ensuring interoperability between codes. Ex: the runtime can execute programs written in any language such as VB.NET, C#.NET and C++.NET with manage extension.

Manage Code

- Code that is developed with a language compiler that target CLR called manage code - Code that is developed without considering the conventions and requirements of runtime

called unmanaged code. Unmanaged code runs in CLR with limited debugging and without garbage collection process.

Garbage Collection Process

It manages allocation and de-allocation of memory for an application. Whenever you create an object, the runtime allocates memory for object from manage heap. The manage heap is a region with one or more pages of reserved address spaces that can be sub divided and allocated in smaller junks. If runtime is unable to locate sufficient memory on manage heap; it invokes garbage collection process which runs through all objects and terminates objects that are no longer used by an application.

(19)

19

Namespaces:

Namespaces helps you to create logical groups of related classes and interfaces that can be used by any language targeting .NET framework. Namespaces allow you to organize your classes so that they can be easily accessed in other application. Namespaces can also be used to avoid any naming conflicts between classes that have same name. Ex: you can use two classes with same name in an application provided they belong to different namespaces. You can access classes belonging to a namespace by simply using namespace name followed by dot (.) and then class name.

Ex: System.console => here System is namespace and console is class name

Assembly:

Assembly is a single deployable unit that contains all information about implementation of classes, structure and interfaces. An assembly stores all information about itself and this information called Meta data and includes the name and version number of assembly, security information and information about dependencies, list of files that constitute assembly. All the application developed using .NET framework made up of assembly. Namespaces are also stored in assemblies. Assemblies and metadata provide the CLR with the information required for execution of an application. Assembly provides this information to CLR while application is being executed. Assembly also plays an important role in deployment and version control.

(20)

20

Manage Code Execution Process

Explanation:

When you compile a program develop in a language that targets the CLR, instead of compiling the source code into machine level code, the compiler translate it to Microsoft Intermediate Language (MSIL) or Intermediate Language (IL). No matter which language has been used to develop the

application, it always gets translated into IL; this ensures language interoperability. Compiler also produces Meta data about the program/ application during process of compilation. Meta data contains description of program such as classes and interfaces, version of components stored in program. IL and metadata linked in an assembly.

When you execute .exe/ .dll file, the IL and other information from base class library is sent to class loader. Class loader loads code in memory.

Before code can be executed, .NET framework needs to convert the intermediate language into native or CPU specific code. JIT compiler translates the code from IL to managed native code. During

(21)

21 process of compilation, JIT compiles only code that is required. During execution, instead of compiling complete code, when an un-compiled method is invoked during execution, JIT compiler converts IL for that method into native code. This process saves the time and memory required to convert complete IL into native code.

During JIT compilation, code is also check for Type Safety. Type Safety ensures that objects are always accessed in a compatible way.

While executing code, a security check is performed to ensure that code has appropriate permission for accessing available resources.

First VB.NET Program

Hello World again!!!

 Open Visual Studio 2010 and click on New Project; a dialog box will open, choose language VB and from application choose Console Application.

 Some key points

o VB.NET is case – Insensitive language

o Console.Writeline is used to print a line on console followed by new line o Console.Write is used to print a line

o Console.Read is used to read a character followed by Enter o Console.ReadKey is used to read a key

o Console.ReadLine is used to read a line followed by Enter o Variable Declaration Review:

(22)

22 Some built in data types:

 Boolean  Byte  Char  DateTime  Decimal  Double  Int16  Int32  Int64  SByte  Single  TimeSpan

 Write the following code in your Console Application code window

(23)

23

Second VB.NET program

Key Points:

 We can use System.Console.Write

System namespace is included in our programs, so it is optional to write System  Convert.int32 is used to convert string to integer type

(24)

24

Third program (using structures)

Key Points:

 Type of VB is replaced by Structure in VB.NET

 In VB, we can change base of arrays by using option base 1, in VB.NET; all arrays are 0 based  Variant data type is not supported in .NET

 Currency data type is replaced by decimal  VB.NET supports shortcuts operators like I += 1

 Dim a, b as integer => in VB.NET a and b both are integers  VB.NET also supports block scope

 Return value of function is supported by return statement  Empty and Null is replaced by Nothing in vb.NET

 Wend is replaced by End While in VB.NET  Boxing : changing value type to reference type  Unboxing : changing reference to value type

(25)

25

Using if-else

Using conditional operator

Key Points:

 Option Explicit ON => it will force you to declare each variable before it is being used  Option Explicit OFF

 Option Strict ON => to stop automatic conversion like from int to long  Option Strict OFF

 ByVal => to pass a parameter by value  ByRef => to pass a parameter by reference

 We can comment a line by pressing ‘ in beginning of a line.  Boolean Operators: o AND o OR o NOT o XOR o ANDALSO o ORELSE

(26)

26

Looping

Assignment:

1. Print table of a number using for loop, do-while loop, do-until loop 2. Read a number from console and check whether it is prime or not

(27)

27

Defining arrays & for-each loop

Subroutine vs. Function

Subroutine cannot return a value while functions can return a value

Subroutine starts with sub keyword and functions start with function keyword

both names are followed by name then parameter list and functions are then followed by return type Subroutines are ended by end sub while functions are ended by end function

While calling subroutine or functions, parenthesis are necessary Calling method is same for both subroutine and functions fun_name ()

sub_name ()

By default arguments are passed by value, we can pass the arguments by using by reference by using byref keyword instead of byval

We can make parameters default/optional by writing optional keyword before byval or byref keywords and specifying their values after variable declaration as

(28)

28

Definition of subroutine and function

Multi dimension arrays

To shrink and grow array size, we use redim

but redim will delete all the data stored in array, to preserve that we use preserve keyword

Retrieving lower and upper bound

Assignment

1. Addition of 2 matrix of order 2X2

2. Initially stores names of 5 students, then change array to hold 10 names and print 10 names using for-each loop

3. Define a function factorial which returns factorial of a number 4. Make a subroutine which swaps two integers

5. Make a subroutine which swaps two integers without using third variable 6. Print following

1 12 123 1234

(29)

29

Using Select-Case

(30)

30

Assignment

1. Overload area() function to calculate area of circle and rectangle. 2. Overload sum() function to sum 2 integers, 2 doubles and 2 strings

3. Overload volume() function to calculate volume of cube, cylinder and cuboid

Defining Classes

(31)

31

Creating constructor

(32)

32

Overloading constructor

(33)

33

Defining Properties

Key Points:

 Properties can be readonly or writeonly also

(34)

34

Operator Overloading

Assignment

1. Overload +,-,*,/ in complex class

a. You can use simple multiplication and division 2. Overload + and – in matrix class of order 3 X 3

(35)

35

Inheritance

Code reusability

Time saving, cost saving

Types of inheritance

Single Level Inheritance Multi level inheritance Hierarchical Inheritance

Variable Scope

Private => accessible in member functions only Protected => accessible in derived class also Public => accessible outside the class also

(36)

36 Inheritance Example

(37)

37

Run Time Polymorphism

Object slicing, Run Time Binding, Late Binding

Early bounding includes Operator overloading and function overloading which we had already covered. In case of runtime polymorphism, which function to be called; will be decided at run-time.

Example

(38)

38

Main2

Run Time Polymorphism

Main3

(39)

39

Assignment:

1. Assume that a bank maintains two kinds of accounts for customers, one called as saving account and other as current account. The savings account provides compound interest and withdrawal facilities but no cheque book facility. The current account provides cheque book facility but no interest. Current account holders should also maintain a minimum balance and if the balance falls below this level, a service charge is imposed.

Create a class account that stores customer name, account number and type of account. From this derive the classes’ cur_acct and sav_acct to make them more specific to their requirements. Include necessary member functions in order to achieve the following tasks:

a. Accept deposit from a customer and update the balance. b. Display the balance

c. Compute and deposit interest

d. Permit withdrawal and update the balance

e. Check for the minimum balance, impose penalty, necessary, and update the balance Don’t use any constructors. Use member functions to initialize the class members.

2. Specify all the classes as shown in figure and define functions to create the database and retrieve individual information as and when required

(40)

40

3. Create a base class called shape. Use this class to shore two double type values that could be used to computer the area of figures. Derive two specific classes called triangle and rectangle from the base shape. Add to the base class, a member function get_data() to initialize base class data members and another member function display_area() to computer and display the area of figures. Override display_area() in derive classes to suit their requireents.

Using these three classes, design a program that will accept dimensions of a triangle or a rectangle interactively, and display the area.

Remember two values given as input will be treated as lengths of two sides in case of rectangles and as base and height in case of triangles, and used as follows:

Area of rectangle = x * y Area of triangle = ½*x*y

4. Extend the above program to display area of circles. This requires addition of a new derived class circle that computes the area of a circle. Remember, for a circle we need only one value, its radius, but the get_data() function in the base class requires two values to be passed. (Hint: Make the second argument of get_data() function as a default/ optional one with zero value)

(41)

41

Abstract Classes

Explanation:

Abstract classes are used to create template for other classes. We can’t create object of abstract classes.

In VB.NET abstract classes are declared by the keyword “mustinherit”

As we can’t create object of abstract class, so there is no use of defining any function, so we declare functions/ subroutine with the keyword “mustoverride”

(42)

42

Interface

Explanation:

~ An alternative to abstract classes

~ less formality as compared to abstract classes

Abstract Class vs. Interface

One abstract class can be inherited Multiple interfaces can be implemented Abstract classes are inherited in derive classes Interfaces are implemented

Members in abstract class can / can’t have definition

Members in interfaces can’t have definition Derive class define functions of abstract class but

not necessary to override all functions

Class implementing interfaces must override / implement all functions declared in interface

(43)

43

Example2

(44)

44

Example3

(45)

45

Non Inheritable Class

As the name is stating, this class can’t be inheritable further.

Example

Enumeration

Key points:

1. Default value is 0 for first name in enumeration 2. Rest all will get incremented value.

(46)

46

Overriding tostring () function

It’s like overloading output operator.

(47)

47

Understanding console

(48)

48

Command Line Arguments

Passing command line arguments

You can pass arguments from command prompt like exefilename firstarg secondarg … For testing purpose you can pass arguments from VSIDE also.

1. Go to project menu and choose <your application> properties. For me, its’ consoleapplication1 properties

2. Choose debug tab from left pane and in command line textbox, write your arguments

(49)

49

Assignment

1. Make a vehicle class, overload properties for registration number and model number. Also override tostring () function in vehicle class

2. Use command line arguments to perform +, - , *, /. For example, user will provide first number then operator and then second number like

a. Consoleapplication1.exe 10 + 20

3. Define a test class in a namespace sample. Define input and output function for the class test and use them in main.

4. Make an enumeration month. User will enter a numeric month, use select case to check the month name and print number of days for the same.

(50)

50

Using VB6.0 File Handling in VB.NET

(51)

51

.NET File Handling

(52)

52

Small-Small Big-Big Functions

Creating directory

Copy one file to another

(53)

53

Understanding System.Environment

Getting User Name

Getting Current Directory

Getting System Directory

Getting Folder Path

Getting Operating System Version

Checking whether it is 64 bit OS or not

(54)

54

Understanding My.Computer

Getting GMT time

Checking various keys like caps lock, num lock, shift etc…

Checking whether mouse is left handed or right handed

Getting computer name

Checking total physical memory

Checking total virtual memory

Checking available physical memory

Checking screen information, resolution etc…

Getting OS platform

Getting culture

File System

(55)

55

Assignment

(56)

56

Generating Random numbers

Using System.Collections

(57)

57

Queue

(58)

58

Using Substring function

Assignment

(59)

59

DateTime functions

Assignment:

1. Write a program to copy one file to another

2. Write a program which read from 2 files and write into third file

3. Write a program which read form one file and copy all even lines to second file and odd lines to third file

4. Write a program which read input lines from users and save them in a file on desktop and then read those lines from file and display it to user

Hint: use getfolderpath() to get path of desktop 5. Write a program for parsing using stack

6. Write a program which converts infix to postfix and evaluate the postfix expression

(60)

60

Exception Handling

I am not covering theory part as every book has long stories on what are exceptions. Here we are directly going to look at procedure to handle exceptions.

1. Find the problem

2. Inform that an error has occurred 3. Receive the error information 4. Take corrective action

Try-Catch

(61)

61

Try – Throw – Multiple Catch

(62)

62

Exception Class

- It’s base class of all other exception classes

- Used basically to handle those exception which programmer either forget to handle or programmer was not able to classify

- Also used to define user defined exceptions

(63)

63

Try – Throw – Catch – Finally

(64)

64

Nested Try

In case inner try was not able to handle the exception, it will search catch in outer try.

(65)

65

Examples of various Exceptions

Try various exceptions at your own.

User – Defined Exception

- It must be inherited from Exception class - You have to override tostring() function - You have to override message property

(66)

66

User – Defined Exception Example

Assignment

(67)

67

Windows Applications

I expect you are comfortable with Microsoft Visual Basic 6.0. Incase you don’t have knowledge about Visual Basic 6.0, I will suggest you to first go thru with that.

Here, we will be referring directly to the some common properties and some common events of controls.

(68)

68

Creating First Windows Application

1. Choose new project

2. From the open dialog box, choose windows application and click okay 3. Form will appear in Design mode

Remember:

In .NET, each control is having text property instead of text and caption property and the most important line, everything is based on namespaces, classes and object is mother of all.

(69)

69 4. Drag the label and double click the form

5. On form_load event write

Remember:

Me refers to current form. In VB.NET, you can’t use current form name in current form class, so we will be use Me if we want to refer to current class.

(70)

70

Second Windows Application

Design a Form like

Change text properties from properties menu. I am here not changing name properties of controls; you can change them as per your convenient.

(71)

71

List of Controls; we will be looking at

1. Form 2. Button 3. CheckBox 4. CheckListBox 5. ColorDialog 6. Combo 7. ContextMenu

8. DataGrid (at a later stage)

9. DateTimePicker 10. DomainUpDown 11. ErrorProvider 12. FontDialog 13. GroupBox 14. HScrollBar 15. Label 16. LinkLabel 17. ListBox 18. ListView 19. MaskedTextBox 20. MenuStrip 21. MonthCalendar 22. NotifyIcon 23. NumericUpDown 24. OpenFileDialog 25. Pannel 26. PictureBox 27. ProgressBar 28. RadioButton 29. RichTextBox 30. SaveFileDialog 31. StatusStrip 32. TabControl 33. TextBox 34. Timer 35. ToolTip 36. ToolStrip 37. TrackBar 38. VScrollBar

(72)

72 39. MediaPlayer 40. WebBrowser 41. AdobePdf 42. TableLayout 43. FlowLayout 44. FolderBrowserDialog 45. PrintDialog 46. PrintForm 47. Animation Control 48. Drawing Graphics 49. MessageBox 50. InputBox

These controls are described in an order to make the reader comfortable and to make learning more interesting.

(73)

73

Label

Properties window:

1. AutoSize : True ( Label will automatically adjust its size ) 2. BackColor : to change its background color

3. BorderStyle : single or 3D

4. ContextMenuStrip : To change right click menu; we will look in detail about this option 5. Cursor : you can change mouse cursor which should appear on this label

6. Dock : Where and how this label should appear 7. FlatStyle : Looks of label

8. Font

9. ForeColor : text color of label

10. Image: Image which will appear on label 11. ImageAlign : Left / Right / Center

12. RightToLeft : If yes, text will appear from right to left 13. Text : text to be appear on label

Events:

(74)

74

TextBox

Properties window:

Same as of label control, some new properties are shown here

1. Multiline = true ( you can write multiple lines in textbox; by default, textbox is single line) 2. Password char = * ( now the text appearing in textbox will be marked as * ; you can use any

character)

3. ReadOnly = True ( now user can read the text of textbox, he can’t modify it) 4. ScrollBar = None / Horizontal / Vertical / Both

5. WordWrap = True

6. TabStop = True ( Using Tab key, you can focus on this control ) 7. TabIndex, to set tab preference, when tab should appear on it. I will recommend you to try all properties of properties window.

(75)

75

Form

Properties window:

1. BackgroundImage 2. BackgroundImageLayout

3. ControlBox = False ( minimize, maximize and close button will not appear) 4. FormBorderStyle ( Try all these options and see effects)

5. MaximizeBox = False (Maximize button will get disable on form) 6. MinimizeBox

7. Opacity (to set transparency of Form, Try using with 80% and 50%, Default is 100%)

8. ShowInTaskbar = False (When you execute your form, your form will not appear in Taskbar) 9. Text = to change title bar text of form

10. TransparencyKey = white ( which color of form you want to be transparent, if I have selected white, then the white color, wherever on form , will be transparent)

(76)

76

Button

Properties window:

Properties are similar to textbox and label, try them at your own.

(77)

77

A Funny Application – Confusion!

1. Design your form like

2. Program it as

(78)

78

Again Confusion!!

1. Design same form again

2. Program it as

(79)

79

CheckBox

Properties window:

1. Checked: (Initially, when form is loaded, this checkbox will be checked or not)

2. ThreeState : True ( Then checkbox can have three states : Unchecked, Checked or intermediate )

Events:

Example:

Design your form as:

(80)

80 Result:

(81)

81

TrackBar

Properties Window:

1. Minimum and Maximum value 2. RightToLeft

3. Orientation : Horizontal or Vertical

Events:

(82)

82

VSrollBar

Example:

Assignment

(83)

83

Timer

Simply drag the timer on your form. When you will drag, it will appear on the bottom bar IDE.

Property Window:

1. Enable: True ( to enable the timer, by default; its false)

2. Interval : duration after which timer will tick (1000 means 1 sec)

(84)

84

LinkLabel

It will appear as a link on form. You can do the normal working on its click event or you can browse some website as it looks states.

(85)

85

ProgressBar

Example:

Simply drag a progressbar on your form. Change its minimum, maximum and style properties (if you want)

Place a timer on your form. Change its interval to 1000 and enable to true And program your timer as below and execute your program.

(86)

86

WebBrowser

Example:

Drag WebBrowser on your form. By Default it is docked in form. Click on Top Right Arrow appearing on WebBrowser Control and choose undock

Design your form as shown below

Initially, we are designing it with buttons, later you can create toolbar or menu bar and also you can use images to change its Design.

(87)

87 And now program it as:

I have changed name of controls to make programming more understandable.

That’s all we have to do and Thanks to Microsoft and our WebBrowser is ready!!!

MaskedTextBox

Use to specify a Mask/ Format.

Change its mask property and try it at your own. It’s similar to TextBox except its mask property. Try this at your own.

(88)

88

RadioButton

Example:

Design your form as:

And program it as:

(89)

89

A Big Confusion!!!

Design your form as:

And program it as:

(90)

90

Confusion Solved

Drag GroupBox from toolbox and design your form as:

And execute your form:

(91)

91

ComboBox

Example:

Design your form as:

and program it as:

(92)

92

Still, Confusion!!!

In above program, check carefully, user is able to change the text of ComboBox. User can edit the text of combo box.

Confusion Solved:

Select the combo box and from properties menu, change its DropDownStyle to DropDownList.

And now execute your form.

(93)

93

ColorDialog

Example:

Simply drag color dialog on your form and program your form as:

(94)

94

FontDialog

Example:

Drag font dialog on your form and design your form with a button and textbox and program it as:

(95)

95

FolderBrowserDialog

Example:

Drag FolderBrowserDialog and a button on form and program it as:

And execute your form and choose a folder and click ok…

Using FolderBrowserDialog, you can ask user to select folder, where he wants to save files, and you can get the path using FolderBrowserDialog.

Note: before showing this dialog, write

FolderBrowserDialog1.ShowNewFolderButton = False

(96)

96

OpenFileDialog

Example:

Drag OpenFileDialog and a button on form and program it as:

And execute your application…

Now you know the file handling; so instead of displaying filename in msgbox, you can read its contents and show in textbox or you can perform some operations. Basic idea is to show you how to use OpenFileDialog.

(97)

97

AdobePdf

Example:

Drag AdobePdf, OpenFileDialog and a button on your form and program it as:

(98)

98

NumericUpDown

Example:

Drag NumericUpDown and a button on form. You can change minimum and maximum value of NumericUpDown from properties menu. Program your button as:

(99)

99

MonthCalendar

Try this at your own. Try out all its properties. It’s generally used to display calendar on form.

DateTimePicker

Using this control, you can get the value (Date) which user has selected.

Example:

Design your form as:

(100)

100

MessageBox

Till now, we are using Msgbox (), but this is a function of VB. Now we will be discussing MessageBox.

Variants of MessageBox:

InputBox

It’s used to take a value from user. It will return a string; you have to convert it to specific type before using.

(101)

101

ListBox

Example:

(102)

102

Configure ListBox for multiple selections

Select ListBox on form and from its properties menu, change its SelectionMode to MultiSimple.

(103)

103 And now execute your form:

(104)

104

CheckListBox

Example:

Drag a CheckListBox and a button on form and program it as:

(105)

105

MenuStrip

Drag the MenuStrip on form. You can directly edit the menus you want to create.

Use – if you want to create separator between menus. And you can assign ALT keys as shortcut by writing & before that character.

(106)

106 You can assign the shortcut keys by choosing that particular item and choose shortcut key from its properties menu. For example: here I want to assign ctrl + s for my save menu

(107)

107

ContextMenuStrip

It’s is similar to MenuStrip except that it doesn’t appear as normal menu bar, you have to assign ContextMenu to some control, where user will right click to see the menu. Here, I am assigning ContextMenu to TextBox as:

(108)

108

ErrorProvider:

Drag a textbox, a button and an error provider on form. Suppose we want to show an error message to user, if textbox. Text is blank. We will write as:

(109)

109

RichTextBox

Have you noticed the difference between notepad and WordPad? In WordPad, you can paste pictures; you can change background and foreground color of selected text, however in notepad, all this is not possible. So, the alternate to TextBox is RichTextBox.

Drag it to your form. By default it is multiline. Let’s look at some of its properties:

Assignment:

Make a Notepad Application using TextBox. Enhance your notepad using RichTextBox.

(110)

110

FlowLayout

Used to draw controls. Like a Panel or GroupBox. Draw a FlowLayout on your form and place your controls inside it. Controls will appear automatically in flowing locations. Try this at your own.

FlowLayout Example:

TableLayout

You will find using FlowLayout is quite difficult because we can’t place controls at desired locations. One alternative is TableLayout. You can place your controls in cells; you can insert some rows and columns and can insert controls in cells. Try this control at your own.

(111)

111

MediaPlayer

Drag MediaPlayer, 3 buttons and an OpenFileDialog on your form and design your form as:

And program them as:

(112)

112 Media Player has lots of properties. Try out all those properties.

(113)

113

ToolTip

Drag a ToolTip and a button on form. Suppose we want to show ToolTip on this button. Select button and from its properties window, choose ToolTip on ToolTip1 and set it to any value.

And now select ToolTip control which you have dragged on form and from its properties menu, you can set its icon, isBalloon and ToolTipTitle.

(114)

114 And now execute your form and move your mouse over Button.

PictureBox

Drag a PictureBox on your form and click on arrow appearing on top right corner; change SizeMode property to different options and check their effects. You can change image of PictureBox in two ways as shown below. Use any one method at a time.

StatusStrip

Drag a StatusStrip on Form; it will appear at the bottom of Form. You can add label, ProgressBar and Dropdown by clicking on the “add new” icon appearing on StatusStrip.

(115)

115 And now you can program them as you want.

Example:

Here, on status label, I want to show the number of characters in RichTextBox.

(116)

116

ToolStrip

To create Toolbar. Drag ToolStrip on Form. By Default, it will appear on top corner. You can change its back color, background image etc… (Check its properties window). Here, I am setting back color to transparent.

There is also an “add new” button appearing on ToolStrip, you can add new items by clicking on it. Suppose we are adding a Button, by default it will appear as image, right click on image button and change its display style like image and text. Now you can change its image by choosing set image option from context menu and its text can be changed from properties menu. Here I have added two buttons:

You can program them by simply double clicking on them. In ToolStrip you can Buttons, Dropdown, Label, Separators, Progress Bar, and TextBox.

(117)

117

Adding Standard items:

Simply select the toolbar. A small arrow will appear on top of toolbar. Click on that and you can add standard items in your toolbar.

(118)

118

TabControl

Drag a TabControl on your form. By default, only two tabs will be shown, you can add or remove tabs by choosing TabPages from its properties menu. You can add your controls in it and program them. Now I leave it to you, how creative you are!

Here are some properties which will help you:

Some Hints:

You can create MultiTab WebBrowser or you can create your notepad and tabbed menu to it.

Printing:

The simplest way, I found is- generate HTML report or open your document thru WebBrowser and user will automatically do the page setup, print preview and print automatically…We don’t have to do all that stuff.

(119)

119

PrintDialog and PrintForm

Drag both PrintDialog and PrintForm on your form and program them as:

Adding Controls at runtime

1. Create an object of control type. 2. Adjust its various properties 3. Set its visibility

4. Bring it to front

5. Set its parent container 6. And finally show it.

(120)

120

Animation:

We don’t have animation control present in our toolbox; we have to add it explicitly. Right click the toolbox and click choose items and from the dialog box, choose com components and from that choose Microsoft Animation Control, and click ok.

(121)

121 Animation Control can play .avi files, search for .avi files available on your PC. Generally, you have seen, while copying files, animation plays on form. We will do something similar. Program your button as:

And now execute your form:

Try out other properties like stop etc…

Note:

Bundle of images and animation comes with VisualStudio2010. You can found them in similar path of the path shown below:

“C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\VS2010ImageLibrary\1033\” Extract files and use them.

(122)

122

Graphics:

Here, we have created a line and a rectangle; there are many functions available for graphics, Again I leave it on you, how creative you are!

Drawing Line and Rectangle:

NotifyIcon

It appears in System Tray.

(123)

123 Note: Don’t forget to set its icon property from property menu.

And now on button_click write

(124)

124

Assignment:

1. Design a Code Module for C++ or Java, like you have Visual Studio for .NET, Similar to this, Design for C++ or Java, so that user don’t have to write so much, Everything Drag and Drop and in background, code will appear automatically and user can view, edit or save it.

(125)

125

Database Connectivity

ADO.NET

Here, I have tried to simplify the Database connectivity. The following figure explains how to connect with database. We are showing here the connectivity with MS-Access, so that you can practice at home. In the similar way, you can connect to SQL Server. MS-Access is not generally used because it can handle only 35 clients at a time while SQL Server and Oracle can handle a large number of clients.

Basic Steps to follow:

1. Create a connection object

2. Set its value like connection string etc… 3. Open the connection

4. Do your work

(126)

126

Displaying all records at a time using Data Adapter and Data Set

1. Open connection

2. Use Data Adapter to read from connection 3. Use Data Set to store data

4. And then display data from Data Set

Open windows application and drag DataGrid on it and program your form as:

(127)

127

Searching using Data Adapter and Data Set

(128)

128

Reading one value at a time using Data Adapter and Data Set

Design a form with just a Label on it and program it as:

(129)

129

Reading one value at a time using command and data reader

Design a form with just a Label on it and program it as:

(130)

130

Searching using command:

(131)

131

Searching using command again:

(132)

132

Insertion into Table using Command:

Deletion using Command:

Update using Command:

Now, I leave up to you, how you will use these commands in your project. Further, You can also add Exception handling in this.

(133)

133 The (copy left) extension:

- You can use the content presented in this for your personal and professional purposes without any permissions.

- All the material presented here is free of cost and hence can’t be charged except distribution charges.

©MillenniumYear Serial: 29062010172738

Références

Documents relatifs

that is high in fat, saturated fatty acids and sugar-sweetened beverages, or if you don’t consume enough fibre, you are at risk for type 2 diabetes. Eat more vegetables, fruits,

An alternative, applied to higher radix digit-recurrence algorithms for division [8, 9], uses prescaling of the operands and rounding of the truncated residual to achieve a

Despite the number of learners in each school and the strict timing, we aimed at gathering high quality data from learners: we needed genuine and dependable infor- mation from

The quality of a data mining method is quantified via an evaluation com- plexity analysis based on the number of supporters and opponents of a pattern extracted by the method..

In order to identify where and to what extent the potential for learning and teaching support and collaborative learning (Naismith et al, 2004) can be realised for initial

results, it was found that this “point-form”, where the dynamical or kinematic character of the Poincar´e generators is the same as for Dirac’s one, implies physics described

Strong concentration for the directed polymer in a random environment for parabolic Anderson model (space dependent only) with a Pareto potential was established in [15].. The

We expect that successful nutrient reduction processes identified during the project (once scaled up) will reduce the concentrations of nutrients within coastal waters and lead to