Documente Academic
Documente Profesional
Documente Cultură
Outline
Toolbox Control Menus and Submenus Dialog Boxes, Message Box and Input Box Data and Operators Control Structure Control Arrays Sub Procedures and Function Procedures
Outline
Debugging Tool Identifying Errors Classes, Objects and Methods Inheritance and Polymorphism Construct using String Methods
Toolbox Control
Windows Graphical User Interface
VB.Net is an object-oriented language Write application programs that run in Windows or on the Internet Window = Form
Menu Editor :
Dropdown Multi-level Pop-up
Dialog Box
Message box
Input box
MessageBox Object
Use Show Method of MessageBox to display special type of window Arguments of Show method
Message to display Optional Title Bar Caption Optional Button(s) Optional Icon
MessageBox Syntax
The MessageBox is an Overloaded Method
Signatures correspond to the Argument list There are multiple Signatures to choose from Arguments must be included to exactly match one of the predefined Signatures
MessageBox.Show (TextMessage, TitlebarText, MessageBoxButtons, MesssageBoxIcon) Example: MessageBox.Show (Good Morning Are You OK Today?, Hello, MessageBoxButtons .YesNoCancel, MessageBoxIcon.Question)
MessageBoxButtons Constants
OK OKCancel RetryCancel YesNo YesNoCancel AbortRetryIgnore
MessageBoxIcon Constants
Warning Exclamation Question Error Stop Information Asterisk
Operators
Arithmetic (+,-,*,/,\,Mod) Logical (Or, And) Relational (=,<>,<,<=,>,>=)
Data Types
byte sbyte Short (sho) ushort 1 byte Range 0 to 255 1 byte Range -128 to 127 2 bytes 2 bytes Unsigned byte Signed byte
Signed integer
4 bytes Range
0 to 4,294,967,295
Unsigned integer
decimal
8 Range bytes A number 28 zeros long string (str) N/A Range N/A char 2 Range bytes 0x0000 to 0xFFFF Bool (bln) True or False
Fixed precision
Unicode
Unicode character
Boolean
VB.NET
Dim intAge As Short Dim intID As Integer
VB.NET
Structure Customer Public CustomerNumber as Integer Public CustomerName As String Public CustomerCompany As String End Structure
Block-Level Scope
VB .NET introduces variables that only exist within blocks of code
Blocks are items such as ForNext, DoLoop, and If ThenEnd If
Variables are only visible within the block, but their lifetime is that of the whole procedure
Changes in Syntax
Firstly the Currency data type is no longer used in VB 6.0 Currency has been replaced with Decimal in VB.NET The Currency data type (64 bit) does not provide sufficient accuracy to avoid rounding errors, so Decimal (96 bit) was created as its own data type. Dim x As Currency is upgraded to: Dim x As Decimal
VB.NET
Long variables are stored as 64-bit numbers, Integer variables are stored as 32-bit numbers, Short variables are stored as 16-bit numbers.
Dim x As Variant
Dim x As Object
is upgraded to:
Arithmetic Operations
Numbers are called numeric literals Five arithmetic operations in VB.NET
+ addition - subtraction * multiplication / division ^ exponentiation
25
Mathematical Operators
Operator + * / \ Mod ^ Operation Addition Subtraction Multiplication Division Integer Division Modulus (division's remainder) Exponentiation
Named Constant
Memory locations that hold data that cannot be changed during project execution Ex: Sales tax percentage, SSI rate
Constants
Named
User defined
Intrinsic
System defined within Visual Studio
Color.red
Variables
Declaration:
Dim speed As Double
Variable name
Data type
Assignment:
speed = 50
29
Initialization
Numeric variables are automatically initialized to 0: Dim varName As Double To specify a nonzero initial value Dim varName As Double = 50
30
5-31
Decision Structures
Controls the program execution path based on condition
Boolean expression is true or false A variable has a specific value An error condition occurs
5-32
5-33
5-34
5-35
If...ThenElse - Syntax
Syntax1 Syntax2
5-36
If...ThenElse - Syntax
Private Sub btnClick1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClick1.Click If TextBox1.Text = "Alexander" Then MessageBox.Show("Hello " & TextBox1.Text, "Greetings", MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub
5-37
5-38
5-39
If...ElseIf...Else structure
Uses different comparison expressions
5-40
5-41
Loops
Program structure that executes a series of program statements multiple times until it reaches an exit condition Pretest loop
First evaluates the exit condition and then executes the program statements
Posttest loop
Executes the program statements first and then evaluates the exit condition
5-42
Do Loop
Can be either a pretest or a posttest loop Syntax
5-43
Do While Loop
Pretest loop that first evaluates a condition
If the Condition is true, the program statements execute and the loop evaluates the Condition again If the Condition becomes false, the loop exits
5-44
5-45
5-46
For...Next Loop
Loop set to iterate a specific number of times Built-in CounterVariable that acts as the counter controlling the number of times the loop executes Loop automatically increments the counter by a StepValue that you specify
5-47
CounterVariable
Specifies the variable that controls the number of times the loop executes
5-48
EndValue
Specifies its end value
StepValue
Specifies the value by which the CounterVariable increments with each loop iteration
5-49
5-50
Stores and manipulates database records that contain columns that have different data types
5-51
Arrays
List of similar data items
One-dimensional array Two-dimensional array Multidimensional array
Useful for storing and processing values that a program reads from a file or database Index
Represents the items position in the array and one or more associated data values
5-52
One-Dimensional Array
Has one data value Syntax {Dim|Private|Public} ArrayName(MaxRows) As DataType
To create a One-dimensional array
5-53
5-54
Two-Dimensional Array
Contains two data values of the same data type Both the columns and the rows have indexes First dimension represents the column index value Second dimension represents the row index value
5-55
5-56
Multidimensional Arrays
Arrays with three or more dimensions Different dimensions are hard to visualize and manage Not often in use
5-57
Array Lists
Composite data type that stores a set of values that can be of any data type Has an index indicating the row position and a value that user associates with the index value Syntax to create an array list
{Dim|Private|Public} ArrayListName As New ArrayList
5-58
Stores the data items as objects rather than as elementary data type values Provides flexibility in working with the list items, whose data type is not known at design time
5-59
Not available with standard arrays Can be used if user does not know how many items will be stored Example - count, sort
5-60
Functions
Always Returns some value Can have zero or more parameters
Procedures
A procedure is a block of Visual Basic statements enclosed by a declaration statement (Sub, Function,Get, Set) and a matching End declaration. All executable statements in Visual Basic must be within some procedure.
If you have code that performs the same task in different places, you can write the task once as a procedure and then call it from different places in your code.
Types of Procedures
1. Sub Procedures A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements. The Sub procedure performs a task and then returns control to the calling code, but it does not return a value to the calling code. It is Public by default, which means you can call it from anywhere in your application. It can take arguments, which are passed to it by the calling code. Types of Sub Procedure They are of 2 types: a) General ProcedureIt tells the application how to perform a specific task. It must be invoked by an application.
b) Event ProcedureEvent procedures execute in response to an event raised by user action or by an occurrence in a program such as click event of an object.
End Sub
Declaration Syntax of Event Procedure [ modifiers]Sub objectname_eventname [(parameterlist )] ' Statements of the Sub procedure. End Sub The modifiers can specify access level (Public, Private)
Parameters
In most cases, a procedure needs to operate on different data each time you call it. You can pass this information to the procedure as part of the procedure call. The procedure defines zero or more parameters, each of which represents a value it expects you to pass to it. By default, all parameters to a VB procedure are passed by reference. When you pass by value, you'll get saved from subtle bugs. Passing by value (ByVal): The procedure gets a copy of the actual value of the argument.
Parameter Declaration
You declare each procedure parameter similarly to how you declare a variable, specifying the parameter name and data type. The syntax for each parameter in the parameter list is as follows: [Optional] [ByVal|ByRef] parametername As datatype If the parameter is optional, you must also supply a default value as part of its declaration. The syntax for specifying a default value is as follows:
Optional [ByVal | ByRef] parametername As datatype = defaultval
Calling Procedure
You invoke a Sub procedure explicitly with a stand-alone calling statement , Call keyword which is optional. The syntax for a call to a Sub procedure [Call] subname [( argumentlist )]
c=a+b
Print c End Sub Private Sub command1_click() Call sum(10,20) Or Sum(10,20) End Sub
2. Function Procedures
A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. The Function procedure performs a task and then returns control to the calling code. When it returns control, it also returns a value to the calling code.
Declaration Syntax of Function Procedure
The syntax for declaring a Function procedure is as follows: [modifiers] Function funcname [(paramlist)] As returntype ' Statements of the Function procedure. functionname = expression Return expression End Function Data TypeEvery Function procedure has a data type. This data type is specified by the As clause in the Function statement, and it determines the data type of the value the function returns to the calling code. Returns control to the code that called a Function, Sub, Get, Set, or Operator procedure
End Sub
End Function
Private Sub command1_click() csum= sum(10,20)
Print csum
End Sub
3. Property Procedures
A property procedure is a series of Visual Basic statements that manipulate a custom property on a module, class, or structure.
VB 6
Public Property Get CustomerName End Property Public Property Let m_CustName = End Property CustomerName() As String = m_CustName CustomerName(sCustName As String) sCustName
VB.NET
Public Property CustomerName() As String Get CustomerName = m_CustName End Get Set m_CustName = Value End Set End Property
[accesslevel]
Get ' Statements of the Get procedure. ' The following statement returns expression as the property's value. Return expression End Get [accesslevel] Set[(ByVal newvalue As datatype)] ' Statements of the Set procedure. ' The following statement assigns newvalue as the property's value.
lvalue = newvalue
End Set End Property
VB Application Files
.sln .suo
May contain multiple projects Stores the names of the project and config info
Project Files
Describes the project and list the files required May contain multiple forms
.vbproj
Project User Options File Form Files Resource File for the Form Code Behind
VB.NET
Public Property CustomerName() As String Get CustomerName = m_CustName End Get Set m_CustName = Value End Set End Property
Default properties are no longer supported. Important! Early Binding is key in VB6 VB 6
txtAddress = rs(Addr_1) lblFName = First Name
VB.NET
txtAddress.Text = rs(Addr_1).value lblFName.Text = First Name
Note: Recordset (COM ADO) is not the preferred data storage object in VB.NET, this is just an example.
VB.NET
Dim intLoop As Integer = 10
VB.NET
Try ... Catch error handling Finally clean up End Try
Modules
Modules are the code container. Visual Basic supports 3 types of modules:
1. Form Module :
It consists of small piece of code called Procedures. It includes the description, settings and properties related to a single form. Its extension is .frm.
2. Standard Module:
It's better to separate all your Functions and Subs and put them somewhere else - in something called a Module. That way, we can use them in other projects. It does not have a GUI and contains only code. It is a container for procedures and declarations commonly used by within the application. They contain global and ,module level declarations of variables. Its extension is .bas.
From the from down menu, click on "Add Module":You'll should see a blank window, with this code in it:
FORM
CALLING OF MODULE
3. Class Module
They are the foundation of Object-oriented programming in Visual Basic. It is used to create new objects. They have no visible user interface.
From the Add Class Module window, click on Open":You'll should see a blank window, with this code in it:
Programming Languages
Procedural
Program specifies exact sequence
Event Driven (VB 6.0 and previous) Object Oriented Programming (VB.NET)
User controls sequence
Click event Double Click event Change event
Class
Programs are complex. A Class is one part of a program. It is self-contained. When we modify a Class, other parts of the program are not affected. This makes programs more reliable and easier to develop.
Class
Class
Software structure that is important in Object Oriented Programming Has data members and methods Blue print or proto type for an object Contains the common properties and methods of an object Few examples are Car, Person, Animal
Object
Instance of a class Gives Life to a class Ram is an object belonging to the class Person Ford is an object belonging to the class Car Jimmy is an object belonging to the class Animal
Constructor
Used for initializing private members of a class Name of the constructor should be New() always Can have zero or more parameters Does not return any value. So they are sub routines Need not be invoked explicitly. They are invoked automatically when an object is created A class can have more than one constructor Every constructor should differ from the other by means of number of parameters or data types of parameters Constructors can be inherited
Example 1
Public Class Test Dim a As Integer Sub Print() MsgBox (Hello) End Sub
Public Function add(ByVal a as Integer, ByVal b as Integer) as Integer Return (a+b) End Function End Class Module M1 Sub Main() Dim t as New Test() Creating Object for the class Test t.print() Calling sub routine print (method) End Sub End Module
Example 2
Module Module1 Sub Main() Dim st As New Student 'create object st.setnumber()' accessing members st.getnumber() Console.ReadLine() End Sub Class Student Private stnumber As Integer Private stname As String Private stsex As String Public Sub setnumber() Console.WriteLine("Enter student's number:") stnumber = CInt(Console.ReadLine) End Sub
VB.NET: Polymorphism
Polymorphism is where multiple procedures of the same name perform different tasks. One name many forms/ one object behaving as multiple forms/ One function behaves in different forms/ Many forms of a single object Polymorphism is the process of using an function or a procedure in different ways for different set of inputs given.
VB.NET: Polymorphism
Public Class RollerCoaster Public Sub Ride() Console.WriteLine("Here we go") Console.WriteLine("Click, Click ,Click") Console.WriteLine("Oh, *&@&#%") Console.WriteLine("That was great") End Sub End Class Public Class MerryGoRound Public Sub Ride() Console.WriteLine("OK will go on it") Console.Writeline("Nap Time") Console.WriteLine("Yea its over") End Sub End Class
VB.NET: Overloading
Functions can now be overloaded (accept arguments of different types) Method with same name but with different arguments. VB.NET:
Overloads Function ConvertSQL(ByVal strString As String) As String ConvertSQL = "'" & strString & "'" End Function Overloads Function ConvertSQL(ByVal intNum As Integer) As String ConvertSQL = CStr(intNum) End Function
VB.NET: Overriding
Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its parent superclass. Class { virtual void hello() Sample : { Console.WriteLine(Hello from Parent); }
}
(not in vb.net)
Class child : parent { override void hello() { Console.WriteLine(Hello from Child); } } static void main() { parent objParent = new child(); objParent.hello(); }
VB.NET: Inheritance
Inheritance allows us to define a class in terms of another class which makes it easier to create and maintain an application, warisan This also provides an opportunity to reuse the code functionality and fast implementation time.
VB.NET: Inheritance
Public Class Customer Private m_CustName As String
Public Property CustomerName() As String Get CustomerName = m_CustName End Get Set m_CustName = Value End Set End Property End Class
Public Class CustCompany Inherits Customer Private m_CustCompany As String Public Property CustomerCompany() As String Get CustomerCompany = m_CustCompany End Get Set m_CustCompany = Value End Set End Property End Class
VB 6 Moving Forward
Avoid
Web Classes, ActiveX Docs, DHTML Apps
Development Techniques
Early Binding Dont use Default Properties Use Constants (such as true) Avoid GoSub Use ByVal and ByRef explicitly (ByVal is now default) Use ADO
References
www.cs.ccsu.edu/~markov/ccsu_courses/introvbnet_ch03.ppt web.sau.edu/grenierkennethr/.../Appendix%20Part%201%20. ppt http://www.dotnetperls.com/class-vbnet http://www.tutorialspoint.com/vb.net/vb.net_classes_objects .htm http://www.vbtutor.in/getting-started-with-visual-basicnet/object-oriented-programming-in-vbnet http://www.worldbestlearningcenter.com/index_files/VB.NET _OOP_Create_Objects.htm http://www.codeproject.com/Articles/602141/Polymorphismin-NET