You are on page 1of 196

| 

à 
á   

‡ The .NET Framework
± Common Language Runtime
± Managed and Unmanaged Code
± MSIL
± JIT
± Assemblies
 
‡ Event Model
‡ Event Handlers
‡ Callbacks
‡ Asynchronous
n rng csnuhr 
‡ Event driven programming and VB .NET
4

_
‡ VS.NET Projects
± Types of Projects
‡ Analyzing structure of project
‡ Using Solution Explorer
‡ Using Server Explorer
‡ Object Browser
‡ Toolbox
‡ Property Window
‡ My First VB.NET App.


‡ Windows Application
± Standard Windows -based applications.

‡ Class Library
± Class libraries that provide similar functionality to Microsoft
ActiveX® dynamic-link libraries (DLLs) by creating classes
accessible to other applications.

‡ Windows Control Library


± User-defined Windows control projects, which are similar to
ActiveX Control projects in previous versions of Visual Basic.

‡ ASP .NET Web Application


± Web applications that will run from an Internet Information
Services (IIS) server and can include Web pages and XML
Web services.


‡ Web Service
± Web applications that provide XML Web Services to client
applications.

‡ Web Control Library


± User-defined Web controls that can be reused on Web
pages in the same way that Windows controls can be
reused in Windows applications.

‡ Console Application
± Console applications that will run from a command line.

‡ Windows Service
± Windows services that will run continuously regardless
of whether a user is logged on or not.
_ !
‡ Solution files (.sln, .suo)
± The .sln extension is used for solution files that link one or
more projects together, and are also used for storing certain
global information.

‡ Project files (.vbproj)


± The project file is an Extensible Markup Language (XML)
document tha contains references to all project items, such as
forms and classes, as w ell as project references and
compilation options.

‡ Local project items (.vb)


± It may contains classes, forms, modules, and user controls
h "#
‡ Displays Project Hierarchy
± Project references
± Forms, classes, modules
± Folders with subitems
‡ ÎShow All Files´ Mode
‡ Manipulating Projects
± l Drag-and-drop editing
± l Context menus
h  "#

‡ Managing Data Connections

‡ Viewing and Managing Servers

‡ Using Drag-and-Drop
Techniques
á$

‡ Examine Objects and their


Members
‡ Access Lower-level Items
± Shows inheritance and
interfaces
‡ Examine How the .NET
Framework Class Libraries
Use Inheritance
"
# %
¢ 
_##

4nrouconosusc 


‡ Leave it in VB6
± WebClasses, ActiveX Documents, DHTML Projects
‡ Thinking in VB.NET
± Data Types, Type vs. Structure
± Property Functions, Zero Bound Arrays
± Default Parameters
‡ New Features
± Forms Designer, Declaration Syntax
± Structured Exception Handling
± Overloading, Inheritance
± Free Threading
‡ ADO.NET

&

‡ Variables
‡ Data Types
‡ Identifiers
‡ Keywords
‡ Literals
‡ Dimensioning Variables
‡ Operators
‡ Expressions
‡ Statements
$
What is a variable?
‡ It is a container (with a name) that holds µstuff¶
‡ Remember Algebra?
X+3=7
X is a variable. It contains/holds/represents a value, that we can
deduce is 4.
$
‡ We must µdimension¶ variables « i.e. tell the computer
that you want one before you use it
± µdeclare¶ a variable (in C)
± The computer allocates memory and then you can put what you
want in it
± You can put only something which the variable can hold ± read
µDATATYPE¶.
 #'( #
‡ Stack Vs Heap
‡ Value types are stored on stack.
± Eg. All primitive types except. String
‡ Reference Types are stored on heap (Managed heap).
± Eg.Class Object
 #
What are Data Types?
‡ Data Types restrict what a variable can hold
‡ Memory is allocated depending on the data type ± text,
number, date
± Text: ³BITS´, ³Visual´, ³Basic´
± Number: 3, 9, 432156
± Dim name as String
‡ name = 7 µWRONG!
 # 
‡ Plenty of them
± String
± Integer
± Boolean (for True/False types)
± DateTime
± Double (for money, fractions)
± And more «
 #)*
‡ Any text value
± Names
± Colors
± Login ids

‡ Examples
± ³Rahul´
± ³Red´
± ³f1997408´
 #)4+
‡ Can hold whole numbers
± Both positive & negative
‡ Examples
± 10
± -666
± 0
 #)' 
‡ Boolean: µLogic¶ values
± Only 2 values possible
± True or false
‡ True: any non-zero value
‡ False: zero

‡ DateTime: To store date in various formats


± 30-01-2004
± 30-01-2004 5:50 PM
± etc
 #)$,
‡ Double: to store Real numbers
Fractions
‡ Examples
± 0.00
± 19.7
± -98.3674501

&

‡ Identifiers
± 4 are names given to types (enumerations,
structures, classes, standard modules, interfaces, and
delegates), type members (methods, constructors, events,
constants, fields, and properties), and variables.
‡ Keywords
± 
 are words with special meaning in a programming
language. In Visual Basic .NET, keywords are reserved; that
is, they cannot be used as tokens for such purposes as
naming variables and subroutines.
± E.g. Binary, Boolean, ByRef, Byte, ByVal, Auto, integer, Float,
else, exit «

&

‡ Literals
° are representations of values within the text of a program.
For example, in the following line of code, 10 is a literal, but x
and y are not:
x = y * 10
± 
   Single, Double, and Decimal
±    
± 
   
 !
"
Dim MyChar As Char
MyChar = "A"c

± #  
±  
$
‡ Two ways
± Dim x as Integer
± Dim x as Integer = 7 µinitialized also here

‡ Points to note
± You can do it only once per procedure
± Variables have a scope
± Access to variables can be defined: Public, Private, etc
á#
‡ Operators are symbols & specify operations to be
performed on one or two operands (or arguments).

‡ Operators that take one operand are called unary


operators. Operators that take two operands are called
binary operators.

‡ Type of Operators:
± Unary Operators
± Arithmetic Operators
± Relational Operators
± String-Concatenation Operators
± Logical Operators
h á#
‡ - (unary minus)
The unary minus operator takes any numeric operand. The value
of the operation is the negative of the value of the operand. In
other words, the result is calculated by subtracting the operand
from zero.

‡ Not (logical negation)


The logical negation operator takes a Boolean operand. The result
is the logical negation of the operand.
_ á#

‡ * (multiplication)
‡ / (regular division)
± The regular division operator is defined for all numeric operands. The
result is the value of the first operand divided by the second operand.
‡ \ (integer division)
± The integer division operator is defined for integer operands (Byte,
Short, Integer, and Long).
± The result is the value of the first operand divided by the second operand, then
rounded to the integer nearest to zero.
‡ Mod (modulo)
± The modulo operator is defined for integer operands (Byte, Short, Integer, and
Long). The result is the remainder after the integer division of the operands.
‡ ^ (exponentiation)

‡ + (addition)
‡ - (subtraction)
(á#
‡ = (equality)
‡ <> (inequality)
‡ < (less than)
‡ > (greater than)
‡ <= (less than or equal to)
‡ >= (greater than or equal to)
‡ Like
‡ TypeOf
-á#
‡ >  $
± The & (ampersand) and + (plus) characters signify string
concatenation.
&á#

 %   %   & 
 %  

‡ And
The result is True if and only if both of the operands are True;
otherwise, the result is False.
‡ Or
The result is True if either or both of the operands is True; otherwise,
the result is False.
‡ Xor
The result is True if one and only one of the operands is True;
otherwise, the result is False.
‡ Not
This is a unary operator. The result is True if the operand is False; False
if the operand is True.

‡ Made up of
± Keywords (like Dim)
± Operators
± Variables
± Constants
± Expressions

‡ Types of statements
± Declaration
‡ Dim x% =10
± Assignment:
variable, field, or property = expression
‡ x=y+3*6
‡ Lblcolor.forcolor=system.drawing.color.red
± Executable
‡ If ± Then ± Else
‡ Function calls

‡ Each statement is a command

‡ Each statement can be on a new line or combined


together with :

‡ Statements can span multiple lines using _

‡ Your program ± a lot of statements that do interesting


things

&4# 

‡ Variables can be declared and initialized in same line

‡ As New syntax does not result in lazy instantiation


à      
‡ Return statement can be used in functions

à   
     

      
         à 
!   " #$%  
&    '(   ) 
* !  
*  

&4# 
‡ Many inconsistencies and idiosyncrasies have been
removed
± Set statement not required/allowed on assignment
± parameters always passed in parentheses
± default parameter passing convention has changed to ByVal
 +(""

    + $%
à  "'",  
  "
  Causes compile-time errors
+( $',-%
",
 
Correct syntax
+( $',-%
*  

  +( $.(/  0   '( à  %


 1   
*  
defined with | semantics
*  

&4# 
‡ Error reporting based on structure exception handling
± Try statements replace On Error GoTo syntax
± On Error GoTo syntax supported for backward compatibility
‡ Try statement provides ability to catch exceptions
± Try statement contains one Try block with guarded code
± Try statement can contain one or more Catch blocks

     $.(/  0   '.(/  (   %


à   "   
2(
Try block  "0("       3 1

  0    *0 " 


    0 " 
Catch block #1 +.0$+  0 " 4) 0-+   %
  0 *0 " 
     0 " 
Catch block #2 +.0$5 0"  (  0 " 4) 0-+   %
!  (
   
( "" 
* 2(
*  

&4# 
‡ Strict type checking improve quality of your code
± Enable using option strict on
± Every variable and parameter must be defined with specific
type
± Many implicit conversions are prohibited
± You are required to write more conversions explicitly

á"  *0"   á
á"    á

  +(""

    + $%
( ""   
*  

*  
® %®% 

  1  4+(6  (-3


   4+(6  (-
      
       
_
%   #
!   " #$%  
&    '(   ) 
* !  
*  

  1  4+(""-3
   4+(""- 0
 1   4+(6  (-
  +(""
     + $%
_
'
_
'
à   
 
%%
 
-  .
à     -" #
( - -7  6  $%
*  
*  
_
‡ If, then, End If
‡ If, Then, Else, End If
‡ Select Case
‡ While Statement
‡ Do « Loop
‡ For « next
‡ Arrays
4. . 4
‡ Allows conditional branching in code

If stars > 4 Then


rating = ³Super Hit´
End If
4. . . 4

If choice = 1 Then
shop = ³Shoppers Stop´
Else
shop = ³Walden´
End if
4. . . 4

If choice = 1 Then
shop = ³Shoppers Stop´
ElseIf choice = 2 Then
shop = ³Big Bazaar´
Else µ for any other choice
shop = ³Walden´
End if

µThe Else must be at the end



‡ A 
 statement executes statements based on the value of an
expression. The expression must be classified as a value and its type
must be a primitive type or ()
.
‡ When a Select Case statement is executed, the 
*%  is
evaluated first, and the Case statements are then evaluated in order of
textual declaration. The first  statement that evaluates to  has its
block executed. If no  statement evaluates to  and there is a
  statement, that block is executed. Once a block has finished
executing, execution passes to the end of the 
statement.

‡ Syntax:
Select Expression1
Case 1
µStatement Block for Case 1
Case 2
µStatement Block for Case 2
Case N
µStatement Block for Case N
Case Else
µCatch All
End Select

dim income as double
select case income
case 0 To 100000
tax=0
case 0 To 100000
tax=0
case 100001 To 150000
tax=0.10 * (income-100000)
case 150001 To 200000
tax=0.15*(income-150000) + 5000
case Else
tax=0.20*(income-200000) + 7500

end select

Select number
case 1, 2, 3
txtresult.text= ³1´
case 4 To 10
txtresult.text= ³2´
case Is < 20
txtresult.text= ³3´
case Is > 20
txtresult.text= ³4´
End Select
% 
‡ Used to iterate through a section of code
‡ Iteration could be indefinite
‡ Has a break condition
± Control comes out when this condition is met
‡ The break condition ± an expression that evaluates to
TRUE or FALSE
% 
Syntax:

While <Expr>
[statements]
End While
% 
‡ Example 1
Dim counter as Integer = 0
Dim value as integer = 0
while value < 30
counter = counter + 1
value = value + 10
end while

Msgbox ³The while loop´ & counter & ³times.´


&#
Syntax:

Do[{while | Until} condition]


[statements]
[Exit Do]
[statements]
Loop
% 
‡ Continues to loop while a certain condition (expression)
evaluates to TRUE
± Stops when condition evaluates to FALSE

Syntax:

Do While <Expr>
[statements]
Loop
%  "#
Dim value as Integer
Dim counter as Integer

Value = 11
Counter = 0

Do While value > 10


counter = counter + 1
value = value ± 1
Loop

Msgbox (³THE DO WHILE LOOP: ³ + counter + ³ times.´


h
‡ Continues to loop until a certain condition (expression)
evaluates to TRUE
± Stops when condition evaluates to TRUE

Syntax:

Do Until <Expr>
[statements]
Loop
h "#
Dim value as Integer
Dim counter as Integer

Value = 9
Counter = 0

Do Until value = 10
counter = counter + 1
value = value + 1
Loop

Msgbox (³THE DO UNTIL LOOPED: ³ + CStr(counter) + ³ times.´)


% 
‡ Depending on the check condition
± Check first and then execute [previous case]
± Execute first and then µCheck¶

Do
[statements]
Loop While <Expr>
%  "#
Dim value as Integer
Dim counter as Integer

Value = 10 µchange these values n observer


Counter = 0

Do
counter = counter + 1
value = value ± 1
Loop While value > 10

Msgbox (³THE DO WHILE VARIANT LOOP: ³ + counter + ³ times.´)


h
‡ Depending on the check condition
± Check first and then execute [previous case]
± Check last and then execute

Do
[statements]
Loop Until <Expr>
h "#
Dim value as Integer
Dim counter as Integer

Value = 9 µchange these values n observer


Counter = 0

Do
counter = counter + 1
value = value + 1
Loop Until value = 10

Msgbox (³THE DO UNTIL VARIANT LOOP: ³ + counter + ³ times.´)


 "
‡ When it is known before hand how many times the
iteration will happen.

Syntax:

For x = i To j
[statements]
Next
- "
Example 1:

For Counter = 1 To 1000


µ skip any values between 100 and 600
If Counter = 100 Then Counter = 601
µ set text value
Text1.Text = Counter
Text1.Refresh µ Update Text1
Next Counter
- "
‡ Steps
± When the jump has to be something other than 1
Ex:

For Counter = 1 To 1000 Step 5


µ skip any values between 100 and 600
If Counter = 100 Then Counter = 601
µ set text value
Text1.Text = Counter
Text1.Refresh µ Update Text1
Next Counter
- "
‡ Looping backwards

For Counter = 2000 To 1 Step -1


µ counting back from 2000 to 1
Text1.Text = Counter
Text1.Refresh µ Update Text1
Next Counter
Msgbox "Count down finished"
"
For I = 1 To 10
if I = 7 then
exit for
end if
Text1.Text = Counter
Text1.Refresh µ Update Text1
Next
_ 

‡ An 
is a reference type that contains variables
accessed through   corresponding in a one-to-one
fashion with the order of the variables in the array.
‡ The variables contained in an array, also called the
 of the array, must all be of the same type, and
this type is called the 
 of the array.
‡ An array has a   that determines the number of
indices associated with each array element. The rank of
an array determines the number of   of the
array.
_ 

_
    :

Dim arr(5) as Integer


Arr(0) = 1
Arr(1) = 2
Arr(2) = 3
Etc

OR

Dim arr(5) as Integer = (1, 2, 3, 4, 5)

ReDim Preserve arr(10)


_ 

Array Declaration:

dim square(2,2) as integer


square(0,0)=1
square(0,1)=2
square(1,0)=3«

OR

Dim rectArray(,) As Integer = {{1, 2, 3}, {12, 13, 14}, {11, 10, 9}}

OR

Dim colors(2)() as String


colors(0)=New String(){"Red","blue","Green"}
colors(1)=New String(){"Yellow","Purple","Green","Violet"}
colors(2)=New String(){"Red","Black","White","Grey","Aqua"}
_ ¢ 
‡ Array.GetLowerBound(rank)
‡ Array.GetUpperBound(rank)
‡ Array.Sort(arr)
‡ Array.BinarySearch(arr, element)
‡ Array.Reverse(MyIntArray)
‡ Array.GetValue(index)
‡ Array.IndexOf(arr, element)
‡ Array.LastIndexOf(arr, element)
‡ Array.copy()
_ #
‡ Array.Length
‡ Array.IsReadOnly (always false)
‡ Array.IsFixedSize (always true)
#$
‡ It refers to as the visibility and life of a data item or
object
Types:
‡ Local/Procedural Scope
‡ Block Scope
‡ Module Scope
&#
‡ Such variable are visible only inside that particular
module/ procedure/ function.
E.g.:
Private Sub button1_Click«
Dim i as integer=10
Dim k=i/5
End Sub

Private Sub button1_Click«


Dim j as integer
Dim j= i*5
End Sub
#
‡ If a variable is declared inside a   (a set of
statements that is terminated by an End..., Loop, or
Next statement), then the variable has  
 ; that is, it is visible only within that block.

For example, consider the following code:


If x <> 0 Then
Dim rec As Integer
rec = 1/x
End If
MsgBox CStr(rec)
¢#
‡ It means that every procedure within that module has
the full access to the data items.
(+
‡ Module scope limits access to the module in which
the definition occurs.

IMP: If two variables with the same name are both in scope, the
most recently defined variable is the variable that is being
accessed.
$/
‡ They are set of instructions designed to accomplish
one specific task.
± They eliminates duplicate code
± Promotes modularity
± Which further leads to ³CODE RESUE´
_
Function RepeatString(ByVal sInput As String, ByVal iCount As
Integer) As String
Dim i As Integer
For i = 1 To iCount
RepeatString = RepeatString & sInput
Next
End Function

‡ The variables sInput and iCount are the parameters of this


function. Note that each parameter has an associated data type.

Now, when we call this function, we must replace the parameters by


variables, constants, or literals, as in:
s = RepeatString("Donna", 4)

‡ The items that we use in place of the parameters are called


arguments.
_
‡ Arguments can be passed in 2 ways:
± ByVal (Call by value):
Passing by value means that the actual  of the argument
is passed to the function.

± ByRef (Call by reference)


if we pass an object variable by reference, we are passing the
address of the variable.
á#_
The following rules apply to optional arguments:
± Every optional argument must specify a default value, and this
default must be a constant expression (not a variable).
± Every argument following an optional argument must also be
optional.
_ 4áá##
‡ Visual Basic .NET provides OOP support
± As powerful as C# or Java
± VB6 programmers must learn many new OOP concepts
‡ New concepts in OOP
± Shared members
± Overloading methods
± Constructors
± Inheritance
± Overridable methods and polymorphism
± Interfaces
± Delegates
± Object finalization and disposal
áá
‡ Encapsulation
Encapsulation is all about the separation between implementation and
interface. It implements Î   

‡ Abstraction
The ability to create an abstract representation of a concept in code.
Its a mechanism and practice to reduce and factor out details irrelevant to
the user.

‡ Inheritance
It allows you to derive new classes from other classes. It is intended to help
reuse of existing code with little or no modification.

‡ Polymorphism
The idea of allowing the same definitions to be used with different types of
data (specifically, different classes of objects), resulting in more general
and abstract implementations.

‡ The idea is that classes are a type.

‡ Class defines the behavior of possibly many objects


(instances).

‡ A class is a blueprint that defines the variables and the


methods common to all objects of a certain kind.
á$
‡ If class is a blueprint, then object is the implementation
of that blueprint.

‡ Each object has data members, corresponding to what


objects knows, and data functions, corresponding to
what an object can do.

‡ A region of storage with associated semantics.


0#0¢ 0 
‡ Fields
The   of a class, also called the class's  , are much
like built-in variables

‡ Properties
Properties are retrieved and set like fields, but are handled with the
u% , and u%  procedures
They provide more control on how values are set or returned

‡ Methods
Methods represent the object's built-in procedures. They are used to
implement the behavior of the
.

‡ Events
Events allow objects to perform actions whenever a specific occurrence
takes place.

To create a class, you only need to use the Class
statement, which, like other compound statements in
Visual Basic, needs to end with End Class:

  *

Public Class DataClass

End Class
"#
Public Class Employee
Private Name as String
Public Salary as Double
End Class
¢$
As discussed earlier, the fields of a class, also called
the class's data members, are much like built-in
variables. They are defined as:
- Public Class Employee
Public Salary As Double
End Class

- Public Class Employee


Public Const PSRN As Integer = 0
End Class
¢$$
‡ Private
± Available only to code within the class
‡ Friend
± Available only to code within our project/component
‡ Protected
± Available only to classes that inherit from our class
‡ Protected Friend
± Available only to code within our project/component and
classes that inherit from our class
‡ Public
± Available to code outside our class
¢ 
‡ As discussed earlier, methods represent the object's
built-in procedures.
‡ You define methods by adding procedures, either Sub
procedures or functions, to your class.
Public Class Animal

Public Sub Eating()


MsgBox("Eating...")
End Sub

Friend Sub Sleeping()


MsgBox("Sleeping...")
End Sub

End Class
¢ 
Public Class Employee µClass Employee defined here
Private m_Tax as double µDeclared Data member

Public Sub Set_Tax(Byval Value as double) µDeclared Function


M_Tax=Value µto set value
End Sub
µanother such function defined below«
Public Function GET_PAYABLE_TAX() As Double
GET_PAYABLE_TAX = m_TAX
End Function

End Class µclass employee end here


#
If you often don't want to give code outside an object
direct access to the data in the object then, you can use
properties, which use methods to set or get an internal
value.

  *

u
u% -%%./   - . %/

,
+  u% |
 ,

  | | _   


u% | 0 |
 

 u%
#
Public Property SET_NAME() As String
µproperty name SET_NAME with return type as string
Get µget starts here for getting this value
SET_NAME = m_NAME
End Get µget ends here

Set(ByVal Value As String) µset starts here


m_NAME = Value µsetting the value of the data
member here
End Set µset property ends here
End Property
!#
‡ Pass parameters to properties

Public Property Pin(ByVal Pincode as String) As String


Get
µWrite the code to get
End Get
Set (ByVal value as String)
µWrite the code to set
End Set
( #
‡ Property to be read only i.e. it cannot be changed

± Public ReadOnly Property Age() as Integer


Get
Return m_age
End Get
End Property
%á #
‡ Value can be changed but cant be retrieved.
± Public WriteOnly Property BirthDate() as Date
Set (ByVal value as Date)
m_BirthDate = value
End Set
End Property
#
‡ Sets the default value
± Default Public Property IsActive (ByVal value As String) As
Boolean
Get
Return True
End Get
Set(ByVal value as Boolean)
m_Is_Active = value
End set
End Property

‡ A constructor is a special member function whose task
is to initialize the objects of it's class.
‡ A constructor is invoked whenever an object of it's
associated class is created.
‡ If a class contains a constructor, then an object created
by that class will be initialized automatically.

Here are the characteristics of a constructor:
‡ Always defined as a Sub. It therefore does not have a
return value.
‡ Regardless the name of the class, the constructor in
VB.NET is called New.
‡ In most cases, a constructor has a Public access
modifier.
‡ A class can have multiple constructors.

e.g.

Public Sub New()


m_name = ""
m_nickname = ""
m_dob = Now.Date
m_email = ""
m_ph = 0
m_mob = 0
m_address = ""
m_org = ""
End Sub
á 
Public Class Employee
private m_name as string

public sub new()


m_name=³´
End sub

public sub new(byval name as string)


m_name = name
End sub

End Class

‡ Destructors run when an object is destroyed. Within a destructor
we can place code to clean up the object after it is used.
‡ We use Finalize method in Visual Basic for this and the Finalize
method is called automatically when the .NET runtime determines
that the object is no longer required.
‡ When working with destructors we need to use the overrides
keyword with Finalize method as we will override the Finalize
method built into the Object class.

Protected Overrides Sub finalize()

µ this distructor is called by Garbage Collector...


µ its called when GC feels like freeing the memory
µ which can even be long after the application exits
MsgBox("DIstructor Called Again BY 'GC' this time´)

End Sub
á$
There are two ways for creating an object. They
are:

' #    _  # 

' #    _ #  0 


# 
#1(

‡ Objects can raise events.
‡ Handles
± Private Sub btnObject_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles button1.Click
± Private Sub MyClickMethod(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles button1.Click,button2.Click

‡ WithEvents
± Makes any events from an object available for use.
± Cannot be used to declare a variable of a type that doesn¶t
raise events.
 
‡ Raise Event
± Define Event
‡ Public Event Brake( )
± Raise Event
‡ RaiseEvent Brake()
± Receive Event (in Form)
‡ Private WithEvents mobjCar As Car
± Receiving Events with AddHandler
‡ AddHandler mobjCar.Brake, AddressOf OnBrake
4- 4#$
‡ Finalize
± GC class Finalize immediately before it collects an object that
is no longer required by application.
± Protected scope and Overrides.
‡ IDisposable
± Force the object cleanup.
± Public Class Car Implements IDisposable
 $
‡ Variable¶s value should be shared across all objects
within the application.
± Private Shared sCounter As Integer
‡ 2 Ways to call
± Call directly from class
± Call from instance
 ¢ 
‡ Common across all instances of the class.
± Shared methods doesn¶t belong to any specific object
± Can¶t access any instance variables from any objects.
± Only variables available for use within shared method are
shared variables,parameters passed into method or variables
declared locally within the method itself.
 #
‡ Follow same rules as regular methods
± Can interact with shared variables, but not member variables
± Can invoke other shared methods or properties
± Cannot invoke instance methods without first creating an
instance of class.
4 
‡ New class can be based on existing class, inheriting its
interface and functionality from original class.
‡ Also referred as generalization or ³is-a´ relationship.
‡ Superclass /Parent Class/ Base Class
‡ Derived Class
‡ Variable Access
± Variables and methods that are Private are available only
within that class.
± Variables and methods that are Public in one class can be
called from other class.
± Variables and methods that are Friend are available between
classes if both the classes are in same VB.NET project.

‡ Virtually any class we crate can act as base class.
 
‡ Inherits Keyword
± Indicates that a class should derive from existing class ±
inheriting interface and behavior from that class.
± Public Class SportsCar Inherits Car
á ¢ 
‡ Overloads Keyword
á ¢ 
‡ Override the behavior of methods on base class
‡ Overridable keyword
¢ 1 
‡ Invoke the methods directly from the base class.
4 
‡ Inherits
± Used to indicate that a class should derive from existing class ±
inheriting interface and behavior from that class
‡ Overloading
± Overloading a method from base class and is done by
Overloads keyword.
‡ Overriding Methods
± Not only Extend the original functionality but actually change or
entirely replace the functionality from base class.
‡ Overridable
± If we don¶t use the keyword when declaring a method, it is non virtual.
‡ Overrides
‡ MyBase
_$
‡ Create a class so that it can only be used as base class
for inheritance.
± MustInherit keyword
‡ Preventing anyone from creating objects based directly on the
class and requiring them instead to create a subclass and then
create objects based on that subclass.
± Public MustInherit Class Vehicle
± MustOverride keyword
‡ Base class also relied on subclass to provide some behavior in
order to function properly.
‡ Class that contaisn methods with MustOverride should be
declared with MustInherit
4
‡ Define the Interface

Public Interface iPrint


µFunction Definitions here!
End Interface
‡ Implementing Interface
± Using Implements keyword
± To implement an interface, we must implement ALL the
methods and properties defined by that interface.
 
‡ All .NET exceptions inherit from System.Exception

?    
Ä  
  
Ä   
  
Ä 

 
 
   
Ä    
Ä    Ä    
Ä    
á 
‡ On Error Goto ErrorHandler
‡ Write ErrorHandler





‡ Try
‡ Catch
‡ Finally
‡ Exit Try
‡ Nested Try
#$
‡ Temporary memory area that holds copied objects
‡ Copied objects can be used in Paste Operation.
‡ DataObject
‡ Clipboard
_$
‡ Private
‡ Shared
 _$
‡ Shared Assembly Names
± Globally unique and must be possible to protect name.
± Must have Strong Name
± Strong Name made up of
‡ Name of Assembly
‡ A Version Number
± Makes it possible to use different versions of same assembly at same
time
‡ Public Key
± Guarantees that the strong name is unique.
± Also guarantees that a referenced assembly can¶t be replaced from
different source.
‡ Culture.
$1  ##
‡ Symmetric Encryption
± Same key can be used for encryption and decryption.
‡ Public/Private Key
± If something is encrypted using a public key, it can be
decrypted by using the corresponding private key, but it is not
possible with the public key. Also works other way round!
± Always created as pair.
4  
‡ Compiler writes the public key to the manifest.
‡ It then creates a hash of all files that belong to
assembly and signs the hash with Private Key.
‡ Private key is not stored within the assembly.
‡ During development , client assembly must reference
the shared assembly.
‡ Compiler writes the public key of referenced assembly
to the manifest of client assembly.
‡ To reduce storage, public key is not written to manifest,
but public key token is written.
‡ Public key token is last eight bytes of a has of public
key and it is unique.
 _$
‡ Create Strong Name
‡ sn ±k mykey.snk
‡ View key using ildasm
‡ GACUtil
± Gacutil /I SharedDemo.dll
h _$
‡ LocalCopy
%® 

  3 4
#  % 1

  # 
# 2# u  
  *
%® 
‡ Us of or
‡ R us of or
‡ M hosnro r s

‡ Properties
± AcceptButton
± CancelButton
± ControlBox
± Font
± Location
± Maximize/Minimize
± Size
± StartPosition
± TopMost
± Window State

‡ Events
± Load Event
± Activated Event (Occurs when the form is activated in code or
by the user.)
± Closing Event
± Closed Event (Occurs when the form is closed)
± Resize

‡ Methods
± Close
± Hide
± Show
± Focus
± Dispose

A control is an object that can be drawn on to the Form to
enable or enhance user interaction with the application.
Example textbox, radiobutton, checkbox etc«
All these Windows Controls are based on the Control class, the
base class for all controls. Visual Basic allows us to work with
controls in two ways: at design time and at runtime.

Some of the properties of this class are:


Allowdrop DataBindings Size
Anchor Dock Width
Backcolor Enable TabIndex
Bottom Focused Text
CanFocus Forecolor Visible etc
CanSelect Font
Cursor Name
"$"
‡ u%  ‡ 1  ‡ 5 
± Text ± AppendText ± Click
± Maxlength ± Clear ± DoubleClick
± Multiline ± Cut ± GotFocus
± Passwordchar ± Copy ± Keydown
± Scrollbars ± Paste ± KeyUp
± SelectedText ± Select« ± KeyPress
± SelectionStart ± MouseHover
± TextAlign ± TextChanged«
± TextLength«
&$
‡ u%  ‡ 1  ‡ 5 
± Text ± Focus ± Click
± Name ± Hide ± DoubleClick
± BackColor ± Show ± GotFocus
± BorderStyle ± Dispose ± Keydown
± Image ± ToString ± KeyUp
± Location ± KeyPress
± Size ± MouseHover
± Visible« ± TextChanged«


‡ u%  ‡ 1  ‡ 5 


± Text ± Focus ± Click
± Name ± Hide ± DoubleClick
± BackColor ± Show ± GotFocus
± BorderStyle ± Dispose ± Keydown
± Image ± ToString ± KeyUp
± Location ± KeyPress
± Size ± MouseHover
± Visible« ± TextChanged«
 "
‡ Property
± Checked
± CheckState
‡ Methods
± OnClick
‡ Events
± Click
± CheckedChange
(
‡ Properties
± Appearance
± BackgroundImage
± Checked
‡ Methods
± OnClick
‡ Events
± Click
± CheckedChange
&"
‡ Properties
± Items
± SelectedIndex
± SelectedItem
± HorizontalScrollbar
± MultiColumn
± SelectionMode
± Sorted
‡ Events
± SelectedIndexChanged
± SelectedValueChanged
&"
‡ To add item
Listbox1.items.add(<value>)
‡ To count no. of items
Listbox1.items.count
‡ To get the selected value
Listbox1.selectedItem
‡ To remove item
Listbox1.items.RemoveAt(index_value)
‡ To remove all the items
Listbox1.items.Clear()
$"
‡ Properties
± Items
± SelectedIndex
± SelectedItem
± Text*
± Sorted
± DropDownStyle
± MaxDropDown
‡ Events
± SelectedIndexChanged
± SelectedValueChanged

‡ Property
± SmallChange
± LargeChange
± Maximum
± Minimum
± Value
‡ Events
± Scroll
± ValueChanged

‡ Property
± SmallChange
± LargeChange
± Maximum
± Minimum
± Value
‡ Events
± Scroll
± ValueChanged
"
The Windows Forms PictureBox control is used to
display graphics in bitmap, GIF, JPEG, metafile, or icon
format.
Properties:
± Image
± Borderstyle
± SizeMode
"
To display a picture at design time
‡ Draw a PictureBox control on a form.
‡ On the Properties window, select the Image property,
then click the ellipsis button to display the Open
dialog box.
‡ If you are looking for a specific file type (for example,
.gif files), select it in the Files of type box.
‡ Select the file you want to display.
"
To set a picture programmatically
‡ Set the Image property using the FromFile method of
the Image class.
e.g.
PictureBox1.Image = Image.FromFile(path)
 
The DateTimePicker control is used to allow the user to select a
date and time, and to display that date/time in the specified format.
Major properties are:

± MaxDate Property
Gets or sets the maximum date and time that can be selected in the
control

± MinDate Property
Gets or sets the minimum date and time that can be selected in the
control
 
± Format Property
Gets or sets the format of the date and time displayed in the control.

± CustomFormat Property
Gets or sets the custom date/time format string. with the appropriate
formatting or custom formatting applied.

± Value Property
Gets or sets the date/time value assigned to the control.


Implements a timer that raises an event at user-defined


intervals.
Properties:
± Enabled Property
Gets or sets whether the timer is running.

± Interval Property
Gets or sets the time, in milliseconds, between timer ticks.

Event:
± Tick Event
Occurs when the specified timer interval has elapsed and the timer
is enabled.

Methods:
± OnTick Method
Raises the ³Tick´ event.

± Start Method
Starts the timer.

± Stop Method
Stops the timer.
( ""
u% 
‡ Color ‡ SelectedText
‡ Font ‡ SelectionLength
‡ Forecolor ‡ SelectionIndent
‡ Zoomfactor ‡ SelectionRightIndent
‡ WordWrap ‡ SelectionBullet
‡ SelectionColor ‡ SelectionAlignment
‡ SelectionFont ‡ SelectionHangingIndent
( ""
Methods Events
‡ LoadFile ‡ LinkClicked
‡ SaveFile
‡ Find
‡ Undo
‡ Redo
"
‡ OpenFileDialog
‡ SaveFileDialog
‡ FontDialog
‡ ColorDialog
( 
Specifies identifiers to indicate the return value of a
dialog box.
± Abort
± Cancel
± Ignore
± Ok
± Yes
± No
± Retry
á#
á#
OpenFileDialog's are supported by the OpenFileDialog class
and they allow us to select a file to be opened.

u% 
± AddExtension: Gets/Sets if the dialog box adds extension to file
names if the user doesn't supply the extension.
± CheckFileEixsts: Checks whether the specified file exists before
returning from the dialog.
± CheckPathExists: Checks whether the specified path exists before
returning from the dialog.
± DefaultExt: Allows you to set the default file extension.
á#
± FileName: Gets/Sets file name selected in the file dialog box.
± FileNames: Gets the file names of all selected files.
± Filter: Gets/Sets the current file name filter string, which sets the
choices that appear in the "Files of Type" box.
± FilterIndex: Gets/Sets the index of the filter selected in the file dialog
box.
± InitialDirectory: This property allows to set the initial directory which
should open when you use the OpenFileDialog.
± MultiSelect: This property when set to True allows to select multiple
file extensions.
± ReadOnlyChecked: Gets/Sets whether the read-only checkbox is
checked.
á#
OpenFileDialog1.Filter = ³Text files (*.txt)|*.txt|" & "All files|*.*´

OpenFileDialog1.Filter =³All Image Files| *.bmp; *.gif; *.jpg´

Dim myfile = OpenFileDialog1.Filename

OpenFileDialog1. InitialDirectory=³c:\abc´

OpenFileDialog1.Title = "My Image Browser"

msgbox(OpenFileDialog1.OpenFile())
á#
One approach is to use the ShowDialog method to display
the Open File dialog box, and use an instance of the
StreamReader class to open the file.

If OpenFileDialog1.ShowDialog() = DialogResult.OK Then


Dim sr As New System.IO.StreamReader(OpenFileDialog1.FileName)
MessageBox.Show(sr.ReadToEnd) sr.Close()
End if
á#
Use the ShowDialog method to display the dialog box and
the OpenFile method to open the file.

Dim openFileDialog1 As New OpenFileDialog()


openFileDialog1.Filter = "Cursor Files|*.cur³
openFileDialog1.Title = "Select a Cursor File"
If openFileDialog1.ShowDialog() = DialogResult.OK Then
Me.Cursor = New Cursor(openFileDialog1.OpenFile())
End If
á#
Dim sr as StreamReader

With OpenFileDialog1
.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"

If .ShowDialog() = DialogResult.OK Then

FileName = .FileName
sr = New StreamReader(.OpenFile)
RichTextBox1.Text = sr.ReadToEnd()

End If
End With
 
 
Save File Dialog's are supported by the SaveFileDialog
class and they allow us to save the file in a specified
location.
Properties:
± Same as that of OpenDialog Box
± OverwritePrompt
Gets or sets a value indicating whether the Save As dialog box
displays a warning if the user specifies a file name that already exists.
 
To save file
1. Open SaveFileDialog Box
2. Declare a stream writer
3. Get the Filename
4. Write into that Filename(from a perticular control)
 
With SaveFileDialog1
.FileName = FileName
.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
If .ShowDialog() = DialogResult.OK Then
FileName = .FileName
End WIth
sw = New StreamWriter(FileName)


+%  
   *   %        

        
u% 
±  u%
Gets or sets the selected font color.
± 4 u%
Gets or sets the selected font.
± 1* 6 u%
Gets or sets the maximum point size a user can select.
±  u%
Gets or sets a value indicating whether the dialog box displays the
color choice.

± 1  6 u%
Gets or sets the minimum point size a user can select.
± 
 u%
Gets or sets a value indicating whether the dialog box contains
controls that allow the user to specify strikethrough, underline, and text
color options.

e.g.
4 # 74 0 * *74
 # 70 * *74
4 # 71* 6 0 82
4 # 71  6 0 79

 4 # 7#  0 # + (: 


* *74 04 # 74
 


Represents a common dialog box that displays available colors along
with controls that allow the user to define custom colors.
Properties:
‡ _4(% u%
Gets or sets a value indicating whether the user can use the dialog
box to define custom colors.
‡ _  u%
Gets or sets a value indicating whether the dialog box displays all
available colors in the set of basic colors

‡ Color Property
Gets or sets the color selected by the user.

‡ CustomColors Property
Gets or sets the set of custom colors shown in the dialog box.

‡ FullOpen Property
Gets or sets a value indicating whether the controls used to create custom
colors are visible when the dialog box is opened

‡ SolidColorOnly Property
Gets or sets a value indicating whether the dialog box will restrict users to
selecting solid colors only.

e.g.
- Dim MyDialog As New ColorDialog()
MyDialog.AnyColor = True
MyDialog.SolidColorOnly = False
MyDialog.AllowFullOpen = True
MyDialog.CustomColors = New Integer() {6916092, 15195440}
If (MyDialog.ShowDialog() = DialogResult.OK) Then
textBox1.ForeColor = MyDialog.Color
End If
¢¢
Menus are those controls that allow the user to make
selections

‡ In Visual Basic, the 1  % control represents the


container for the menu structure of a form

‡ Menus are made up of 1  objects that


represent the individual parts of a menu
¢4
‡ Menus like File or Edit and the actual items in such
menus are supported with the 1  class

Properties:

Checked Property
Gets or sets a value indicating whether a check mark appears next
to the text of the menu item.

MdiList Property
Gets or sets a value indicating whether the menu item will be
populated with a list of the Multiple Document Interface (MDI) child
windows that are displayed within the associated form.
¢4

 u%
Gets or sets a value indicating the shortcut key associated with the
menu item.

 u%
Gets or sets a value indicating whether the shortcut key that is
associated with the menu item is displayed next to the menu item
caption.
* u%
Gets or sets a value indicating the caption of the menu item.
|   u%
Gets or sets a value indicating whether the menu item is visible.
_ ¢4
‡ You can use the 
; property of a 1 
object to toggle the checkmark
± True (checkmark is displayed )
± False (its hidden)

MenuItem.Checked = Not MenuItem.Checked


¢ 
‡ To display the shortcut next to the menu item's caption
at run time, you set the 
 property to True

menuItem.Shortcut = Shortcut.CtrlX
 ¢42#( 

‡ To change a menu item's caption at run time, you only


have to set its * property.

MenuItem.Text = ³My Menu Item´

Note: Try and make use of Popup event in case if u want


to change the caption of a menu item
  ¢4
‡ To show and hide menu items, you can use their Visible
property
± True (Menu Item will be visible)
± False (Menu Item will become invisible)

MenuItem.Visible = False
$¢4
‡ To disable, or "gray out" a menu item, so that it can't be
selected, you set its Enabled property to False.
± True (User will be able to interact with it)
± False (No interaction possible)

MenuItem5.Enabled = False
¢4_##
MDI (Multiple Document Interface) Application is an application
in which we can view and work with several documents at once.

To create an MDI Application:

Select a Form and in it's Properties Window under the Windows


Style section, set the property IsMdiContainer to True. Setting it
to true designates this form as an MDI container for the child
windows.
¢4_##
‡ CREATING MDI CHILD FORMS:

An vital constituent of Multiple Document Interface (MDI)


Applications is the MDI child forms, as these are the main windows
for client interaction.

To create MDI child forms:

Form frmchild = new Form()


frmchild.MDIParent = me
frmchild.Show()
¢4_##
‡ Determining the Active MDI Child
To specify the correct form, use the ActiveMDIChild
property, which returns the child form that has the focus
or that was most recently active.

e.g.
Dim activeChild As Form = Me.ActiveMdiChild
¢4_##
‡ Sending Data to the Active MDI Child

1. Find the Active MDI Child form


Dim activeChild As Form = Me.ActiveMdiChild

2. Find the control on that active form to refer to


<var_name> = CType(activeChild.ActiveControl, <control_type>)

3. Perform appropriate action« like


rtb.LoadFile(.FileName, RichTextBoxStreamType.PlainText)
¢4_##
ARRANGING CHILD FORMS:

‡ Applications will have menu commands for actions such as Tile,


Cascade, and Arrange, with concerning to the open MDI child
forms. One can use the LayoutMDI method with the MDILayout
enumeration to rearrange the child forms in an MDI parent form.

e.g.

- Me.LayoutMdi(MdiLayout.TileVertical)
- Me.LayoutMdi(MdiLayout.TileHorizontal)
- Me.LayoutMdi(MdiLayout.Cascade)
#1(
á¢
‡ Default Interop Assembly
± TlbImp.exe
± Tlbimp MCalculator.dll /out:MCalculatorNet.dll /verbose
&
‡ Reflection
± Type.GetTypeFromProgID
‡ Create Instance
± Activator.CreateInstance
‡ Invoke Member
± Parameter 1: Method to call
± Parameter 2: BindingFlags enumeration tells to invoke the
method
± Parameter 3: Language specific binding information
± Parameter 4: Reference to COM object.
± Parameter 5: Array of objects representing the arguments for
method.
&&

‡ Create a Class Library
‡ Regasm
± Used to register the DLL.
± Regasm MyCalculator.dll /tlb:MyCalculator.tlb

‡ Creating/Extending Control
‡ Extender /Ambient
‡ Creating User Control
(
‡ Ability to inspect and manipulate program elements at
runtime.
‡ Allows you:
± Enumerate the members of a type
± Instantiate a new object
± Execute the members of an object
± Find out information about a type
± Find out information about an assembly
± Create and compile new assembly.
‡ System.Type
‡ System.Reflection
 
#
‡ Holds the reference to a type
Dim t As Type
Dim d As Double = 10
t = d.GetType()
/_
‡ Any Questions please?

You might also like