Anda di halaman 1dari 111

Vipul J Joshi Narsinhbhai Institute of Computer Studies and Management(NICM) Kadi

A storage location in memory (RAM)


Holds data/information while the program is running These storage locations can be referred to by their

names Every variable has three properties:


Name - reference to the location - cannot be changed Value - the information that is stored - can be changed

during program execution, hence the name variable Data Type - the type of information that can be stored cannot be changed

You the programmer make up a name for the variable Visual Basic associates that name with a location in the computer's RAM The value currently associated with the variable is stored in that memory location You simply use the name you choose when you need to access the value

Copy and store values entered by the user Perform arithmetic manipulation on values Test values to see if they meet a criteria Temporarily

hold and manipulate the value of a control property Hold data/information so that it can be recalled for use at a later point in the code

Data type - Specifies type of data variable can store


Integer variables: Long, Integer, Short, Byte Floating-point variables: Single, Double Fixed decimal point variable: Decimal Boolean variables: True, False Character variable: Char Text variable: String The Object variable
Default data type assigned by Visual Basic
Can store many different types of data Less efficient than other data types

Data type
Byte Short Integer Long Single Double Decimal
Char Boolean String Date Object

Prefix Size
byt shr int lng sng dbl dec
chr bln str dtm obj

Values
positive integer value from 0 to 255 integer from 32,768 to +32,767 integer from +/- 2,147,483,647 integer from +/- 9,223,372,036,854,775,807

1 byte 2 byte 4 byte 8 byte

4 byte single-precision, floating-point number 8 byte double-precision, floating-point number 16 byte number with up to 28 significant digits
2 byte Any single character 2 byte True or False (4 byte) Text - Any number/combination of characters 8 byte 8 character date: #dd/mm/yyyy# (4 byte) An address that refers to an object

First character must be a letter or underscore Must contain only letters, numbers, and

underscores (no spaces, periods, etc.) Can have up to 255 characters Cannot be a VB language keyword Naming Conventions
Should be meaningful Follow 3 char prefix style - 1st 3 letters in lowercase

to indicate the data type After that, capitalize the first letter of each word Example: intTestScore

variable declaration is a statement that creates a variable in memory Syntax: Dim VariableName As DataType
Dim (short for Dimension) - keyword VariableName - name used to refer to variable As - keyword DataType - one of many possible keywords to

indicate the type of value the variable will contain


Example:

Dim intLength as Integer

starting or initialization value may be specified with the Dim statement Good practice to set an initial value unless assigning a value prior to using the variable Syntax: Dim VariableName As DataType = Value
Just append " = value to the Dim statement = 5 assigning a beginning value to the variable

Example:

Dim intLength as Integer = 5

Variable MUST be declared prior to the code

where they are used


Variable should be declared first in the

procedure (style convention)


Declaring an initial value of the variable in the

declaration statement is optional


Refer to default values (next slide)

Data type
All numeric types Boolean Char String or Object Date

Default (Initial) value


Zero (0) False Binary 0 Empty 12:00 a.m. on January 1, 0001

Actual value/data/information Similar to a variable, but can NOT change during the execution of a program. Examples of Literals:
Numeric: 5 ; 157 ; 195.38256 String: Paul ; Hello!!! ; Jackson, AL 36545 Char: a ; 1 ; ? ; @ Boolean: True ; False

Programs often need to use given values


For example: decTotal *= 1.06 Adds 6% sales tax to an order total

Two problems with using literals for these types of values


The reason for multiplying decTotal by 1.06 isnt

always obvious If sales tax rate changes, must find and change every occurrence of .06 or 1.06

Use of named constants resolves both these issues Can declare a variable whose value is set at declaration and cannot be changed later: Syntax: Const CONST_NAME As DataType = Value
Looks like a normal declaration except: Const used instead of Dim An initialization value is required By convention, entire name capitalized with underscore characters to separate words

The objective of our code is now clearer


Const sngSALES_TAX_RATE As Single = 1.06 decTotal *= sngSALES_TAX_RATE

Can change all occurrences in the code simply by changing the initial value set in the declaration
If tax rate changes from 6% to 7% Const sngSALES_TAX_RATE As Single = 1.07

What Indicates the part of the program where the variable can be used When From the variable declaration until the end of the code block (procedure, method, etc.) where it is declared

Variable cannot be used before it is declared Variable declared within a code block is only visible to

statements within that code block


Called Local Variable

Can be declared at the beginning of the class code window

(General Declarations section) and be available to all blocks


Called Form Level Variable

Variables that share the same scope cannot have the same

name (same name ok if different scope)

What Indicates the part of the program where the variable exists in memory When From the beginning of the code block (procedure, method, etc.) where it is declared until the end of that code block

When the code block begins the space is created to hold

the local variables


Memory is allocated from the operating system

When the code block ends the local variables are destroyed
Memory is given back to the operating system

Syntax: variablename = expression Assigns the value of the expression to the variable. (The variable must be on the left and the expression on the right.) Example:

intNumber1 = 4 intNumber2 = 3 * (2 + 2) intNumber3 = intNumber1 IntNumber1 = intNumber1 + 6

A value of one data type can be assigned to a variable of a different type


An implicit type conversion is an attempt to automatically

convert to the receiving variables data type

A widening conversion suffers no loss of data


Converting an integer to a single Dim sngNumber as Single = 5

A narrowing conversion may lose data


Converting a decimal to an integer
Dim intCount = 12.2

intCount becomes 12

VB provides a set of functions that perform data type conversions These functions will accept a literal, variable name, or arithmetic expression The following narrowing conversions require an explicit type conversion

Double to Single Single to Integer Long to Integer

Boolean, Date, Object, String, and numeric types represent different sorts of values and require conversion functions as well

Ctype CBool CByte CChar CDate CDbl CDec CInt CLng CObj CShort CSng CStr

Usage Convert to Bool data type Convert to Byte data type Convert to Char data type Convert to Date data type Convert to Double data type Convert to Decimal data type Convert to Int data type CType (converting Var,Datatype) Cpnvert to Long type CType is compiled in-line, meaning the Convert to Object type conversion code is part of the code that Convert to Short data type evaluates the expression. Execution is faster because there is no call to procedure to Convert to Single data type perform the conversion Convert to String type

The Val function is a more forgiving means of performing string to numeric conversions Uses the form Val(string) If the initial characters form a numeric value, the Val function will return that Otherwise, it will return a value of zero

Val Function Val("34.90) Val("86abc) Val("$24.95) Val("3,789) Val(") Val("x29) Val("47%) Val("Geraldine)

Value Returned 34.9 86 0 3 0 0 47 0

Returns a string representation of the value in the variable calling the method Every VB data type has a ToString() method Uses the form VariableName.ToString For example
Dim number as Integer = 123 lblNumber.text = number.ToString

Assigns the string 123 to the text property of the

lblNumber control

Notice that ToString() is a method, not a property. It returns a value that you can assign to a string variable or pass as arguments to a function such as MsgBox(), but the original value is not affected. The ToString method can also format a value if called with an optional argument. ToString(formatString)

Dim Amnt As Single = 9959.95 Dim strAmnt As String strAmnt = Amnt.ToString(C) Or use the following picture numeric format string:
strAmnt = Amnt.ToString($#,###.00)

Output: Both statements will format the value as $9,959.95.

Dim Amount As Decimal = 42492.45 Debug.WriteLine(Amount.ToString($#,###.00)) $42,492.45 Amount = 0.2678 Debug.WriteLine(Amount.ToString(0.000)) 0.268 Amount = -24.95 Debug.WriteLine(Amount.ToString ($#,###.00;($#,###.00))) ($24.95)

We used variables to store individual values. As a matter of fact, most programs store sets of data of different types. For example, a program for balancing your checkbook must store several pieces of information for each check: the checks number, amount, date, and so on. All these pieces of information are necessary to process the checks, and ideally, they should be stored together. You can create custom data types that are made up of multiple values using structures. A VB structure allows you to combine multiple values of the basic data types and handle them as a whole. For example, each check in a checkbook-balancing application is stored in a separate structure

Syntax:
[ Public | Protected | Friend | Protected Friend | Private] Structure structName Dim variable1 As varType Dim variable2 As varType ... Dim variablen As varType End Structure In the above syntax structName is the name of the user defined datatype, that follows the naming convention of a variable. Public option makes these datatypes available in all projects, modules, classes. If declared Private the user defined datatypes can be used where it is declared, same applies to Friend and Protected Friend. variable1 is the name of the element of an user defined datatype. type is the primitive datatype available in visual basic

Example:

Structure Empdetails Dim EmpNo As Integer Dim EmpName As String Dim EmpSalary As Integer Dim EmpExp As Integer End Structure *Event Scope Dim TotalSal As Empdetails TotalSal.EmpNo = TextBox1.Text TotalSal.EmpName = TextBox2.Text TotalSal.EmpSalary = TextBox3.Text TotalSal.EmpExp = TextBox4.Text TextBox5.Text = Val(TotalSal.EmpSalary) * Val(TotalSal.EmpExp) *End of Event Scope

A standard structure for storing data in any programming language is the array. Whereas individual variables can hold single entities, such as one number, one date, or one string Arrays can hold sets of data of the same type (a set of numbers, a series of dates, and so on). An array has a name, as does a variable, and the values stored in it can be accessed by an index.

Unlike simple variables, arrays must be declared with the Dim (or Public) statement followed by the name of the array and the index of the last element in the array in parentheses for example:
Dim intSalary(15) as Integer

It holds the value of 16 persons. To assign values you can write


intSalary(0) = 25000

Arrays, like variables, are not limited to the basic data types. You can declare arrays that hold any type of data, including objects.
Dim colors(2) As Color colors(0) = Color.BurlyWood colors(1) = Color.AliceBlue colors(2) = Color.Sienna

The other way to store multiple values is by using structure Dim Emps(15) As Employee

Structure Employee Dim Name As String Emps(2).Name = Hello All Dim Salary As Decimal Emps(2).Salary = 62000 End Structure

Just as you can initialize variables in the same line in which you declare them, you can initialize arrays, too, with the following constructor.
Dim arrayname() As type = { entry0, entry1, ... entryN } Dim Names() As String = {Hello, All}

This statement is equivalent to the following statements


Dim Names(1) As String Names(0) = Hello Names(1) = All

The first element of an array has index 0. The number that appears in parentheses in the Dim statement is one fewer than the arrays total capacity and is the arrays upper limit (or upper bound). The index of the last element of an array (its upper bound) is given by the method GetUpperBound, which accepts as an argument the dimension of the array and returns the upper bound for this dimension. The arrays we examined so far are one-dimensional and the argument to be passed to the GetUpperBound method is the value 0. The total number of elements in the array is given by the method GetLength, which also accepts a dimension as an argument. The upper bound of the following array is 19, and the capacity of the array is 20 elements:

Dim Names(19) As Integer

The first element is Names(0), and the last is Output: 0

Names(19). Debug.WriteLine(Names.GetLowerBound(0)) Debug.WriteLine(Names.GetUpperBound(0))

Output: 19 You can also use length() property of array to retrieve the count of element

Dim a(,) As Integer = {{10, 20, 30}, {11, 21, 31}, {12, 22, 32}} Console.WriteLine(a(0, 1)) will print 20 Console.WriteLine(a(2, 2)) will print 32 Debug.WriteLine(numbers.Rank) 2 dimensions in array

Dynamic arrays are array that are declared using a Dim statement with blank parenthesis initially and are dynamically allocated dimensions using the Redim statement. The Preserve keyword is used with Redim to preserve the existing elements intake.

Module Module1 Sub Main() Dim a() As Integer = {2, 2} Dim i, j As Integer Console.WriteLine("Array before Redim") For i = 0 To a.GetUpperBound(0) Console.WriteLine(a(i)) Next ReDim Preserve a(5) Console.WriteLine("Array after Redim") For j = 0 To a.GetUpperBound(0) Console.WriteLine(a(j)) Next Console.ReadLine() End Sub End Module

Arithmetic Operators
^ * / \ MOD + & Exponential Multiplication Floating Point Division Integer Division Modulus (remainder from division) Addition Subtraction String Concatenation (putting them together)

Examples of use:
decTotal = decPrice + decTax decNetPrice = decPrice - decDiscount dblArea = dblLength * dblWidth

sngAverage = sngTotal / intItems


dblCube = dblSide ^ 3

The backslash (\) is used as an integer division operator The result is always an integer, created by discarding any remainder from the division Example
intResult = 7 \ 2

result shrHundreds = 157 \ 100 result shrTens = (157 - 157 \ 100 * 100) result

is 3 is 1 \ 10 is ?

This operator can be used in place of the backslash operator to give the remainder of a division operation
intRemainder = 17 MOD 3 dblRemainder = 17.5 MOD 3

result is 2 result is 2.5

Any attempt to use of the \ or MOD operator to perform integer division by zero causes a DivideByZeroException runtime error

Concatenate: connect strings together Concatenation operator: the ampersand (&) Include a space before and after the & operator Numbers after & operator are converted to strings How to concatenate character strings
strFName = "Bob" strLName = "Smith" strName = strFName & " strName = strName & strLName intX = 1

Bob

Bob Smith

intY = 2 intResult = intX + intY strOutput = intX & + & intY & = & intResult

1 + 2 = 3

Often need to change the value in a variable and assign the result back to that variable For example: var = var 5 Subtracts 5 from the value stored in var
Operator += -= *= /= \= &= Usage x += 2 x -= 5 x *= 10 x /= y x \= y x &= . Equivalent to x=x+2 x=x5 x = x * 10 x=x/y x=x\y x = x & . Effect Add to Subtract from Multiply by Divide by Int Divide by Concatenate

Operator precedence tells us the order in which operations are performed From highest to lowest precedence:

Exponentiation (^) Multiplicative (* and /) Integer Division (\) Modulus (MOD) Additive (+ and -)

Parentheses override the order of precedence Where precedence is the same, operations occur from left to right

Parenthesis Exponential Multiplication / Division Integer Division MOD Addition / Subtraction String Concatenation Relational Operators (< , > , >= , <= , <>) Logical Operators (AND, OR, NOT)

6 * 2 ^ 3 + 4 / 2 = 50 7*4/26=8 5 * (4 + 3) 15 Mod 2 = 34

intX = 10 intY = 5 intResultA = intX + intY * 5 iResultB = (intX + intY) * 5 dResultA = intX - intY * 5 dResultB = (intX - intY) * 5

'iResultA is 35 'iResultB is 75 'dResultA is -15 'dResultB is 25

The Condition is evaluated runtime and depending on the result of condition block of code will execute. Control structure also known as Branching statements or Decision structure Control Structure includes:
If.....Then.....Else Select Case

It will execute some logic when a condition become true goes to If and some other logic when the condition is false goes to Else. It is always perform results for comparison of two values.
If condition Then Logic... ElseIf condition-n Then Logic... Else Logic.... End If

If

IsNumeric(txtNo.Text) Then lblAns.Text = Yes its Numeric End If If txtNo.Text Mod 2 =0 Then lblAns.Text = Its Even Else lblAns.Text = Its Odd End If Use with Logical Operators If no1<5 AndAlso no2>10 Then n1= txtNo1.Text lblAns.Text = Its Ok n2= txtNo2.Text Else If no1 > no2 Then lblAns.Text =Not Good lblAns.Text = no1 & Big End If ElseIf no2>no1 Then lblAns.Text = no2 &Big Else lblAns.Text = Both Equal End If

When we are comparing the same expression with several values , then we can use Select....Case statement as and alternative of If...Then...Else We can use the To keyword for range of values We can also use Is keyword for specific comparision

Select Case expression Case expression-n Logic Case Else Logic End Select

Dim intAge as Integer = txtAge.Text Select Case intAge Case 2 lblAns.Text = Your days for Playing Case 3,4 lblAns.Text = Are u in KG Right ! Case 5 To 12 lblAns.Text = You r in Primary School Case 13 To 15 lblAns.Text = You r in Secondary Case Is <18 lblAns.Text = You r Higher Secondary Case Else lblAns.Text = No Idea End Select

Looping structure are used when a group of statements is to be executed repeatedly until a condition become True or False VB.Net supports the follwoing loop structures
For Next Do Loop While End While For each Next

The For loop executes a block of statements a specific number of time


For counter = start To end [Step increment/decrement] Logic Next

Remember that Next keyword should be used in For....Next at the end.

Dim I as Integer For I=0 To 10 Step 1 Logic... Next Dim I as Integer For I=0 To 10 Logic... Next Dim For For For I,J,K as Integer I=1 To 50 J=1 To 30 K=1 To 10 Dim I,J as Integer Logic... For I=1 To 50 Next Next Next For J=1 To 30 Logic... Next J,I

Dim I as Integer For I=50 To 1 Step -2 Logic... Next

Dim I as Integer For I=1 To 100 Step 2 Next

While loop keeps executing until the condition against which it tests remain true. The While statement always checks the condition before it begins the loop. In While loop programmer have to maintain or keep track of increment or decrement value. Dim no As Integer=5
While condition Logic End While While no>0 MsgBox(no) no=no-1 End While

Repeats a block of statments while a Boolean condition is False or until the condition becomes True.

Do { While | Until } condition Do Logic......... Logic......... Loop Loop { While | Until } condition

We can use either While or Until. While: Repeat loop until condition is False. Until : Repeat the loop until condition is True.

Dim no As Integer = 5 Dim ans As Integer =1 Do Until no>= 1 ans =ans *no no=no-1 Loop MsgBox(Fact & ans)

Dim no As Integer = 5 Dim ans As Integer =1 Do While no>= 1 ans =ans *no no= no-1 Loop MsgBox(Fact & ans)

You use the For Each... Next loop to loop over elements in an array or visual basic collection. This loop is great, because it automatically loops over all the elements in the array or collection- you dont have worry getting the loop indices for make sure to get all the elements.
For Each element In group Logic.... Next

Dim ctl As new Control Dim cnt As Integer For Each ctl In me.Controls If TypeOf ctl Is TextBox Then cnt = cnt +1 End If Next MsgBox(cnt)

TypeOf....Is Operator:
This operator is chechked first parameter with

second type that whether given object is and object of Is a given class.

This is not a type of Loop Executes a series of statements making repeated reference to a single object. The use of it do not require calling a name of object again and again. To make this type of code more efficient and easier to read, we use this block
With object Name Logic End With

// Setting up properties of my button by using code With btnAns .Text = Click Me .ForeColor = Color.Green .BackColor = Color.White .Height= 50 .Width=100 End With

A procedure is a set of one or more program statements that can be run or call by referring to the procedure name. Divide the big program into small procedures An application is easier to debug and easy to find error. Reusability of code. Two types of procedures are In-built or User- defined procedure. VB.Net have following type of procedures Sub procedures does not return value. Event-handling procedures are sub procedure that execute in response to an event is triggered(Button1_Click) Function procedures return a value Property procedures used in object oriented concept

A sub procedures is nothing more than a small block of program in itself. It is also known as Sub Routine There are 2 parts for declare and calling Sub procedure may or may not have arguments . Arguments are not compulsory It does not return the value By Val is by default argument type.
[accessibility] Sub SubName [(ParameterList)] [Logic.] End Sub

Public Class SubProdedure


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Hi(12, 15) // call Hi(12,15)

Sub Hi(ByVal a As Integer, ByVal b As Integer) MsgBox("Hello I am Here End Sub " & "" + (a + b).ToString)

End Class

A Function procedure is similar to a sub procedure, but it return a value to the calling program. Function may or may not have argument By Val is by default argument type As clause is written after the parameter list is set. It return a value so call function using: varname= functionName(argument) By default function are public

[Modifiers] Function FunctionName [(ParameterList)] As ReturnType Statements Return Values] End Function

Function add(ByVal s1 As Integer, ByVal s2 As Integer) As Integer Return s1 + s2 End Function

We can specify procedure argument as an optional like in C++ (default argument) Its not compulsory to pass for calling it It should be indicate by Optional keyword with default value other wise it overwritten with default value. Optional argument must be at last declare

Function add(ByVal s1 As Integer, Optional ByVal s2 As Integer =1) As Integer Return s1 + s2 End Function ----------------------------------------------------------------Sub ad(ByVal s As Integer, Optional ByVal v As Integer = 1) MsgBox(s + v) End Sub

There are two ways to pass arguments:


By Val (By Value)

Default in VB.NET By Ref (By Reference)

By Val: refers to pass a copy of a variable to procedure. We can make changes to the copy and the original will not be altered. Variable itself will not change with in the procedure By Ref: refers to actual argument(memory address) itself is passed for the same variable and arguments

Sub Button Click Dim x,y As Integer x= txt1.Text y= txt2.Text Swap(x,y) txt3.Text = x txt4.Text=y End Sub Sub Swap(By Val a As Integer,By Val b As Integer) Dim temp As Integer temp=a a=b b=temp End Sub

3 ways to pass arguments


Passing Args. by Position(Ordered) Passing Args. by Name (Use varname and :) Mixing Args. by Position and by Name

FO is the implementation of Polymorphism concept of the OOP. In VB.Net we can declare two or more procedure with same name When we declare more than one prodedure with the same name but number argument may be differing, types of arguments may be differ or sequence of thoes argument may be differ.

Private Sub btn_Click() add(...........) End Sub ---------------Sub add() logic End Sub -----------------Sub add(ByVal no As Integer) logic End Sub -----------------Sub add(ByVal no1 As Integer, ByVal no2 As Integer) logic End Sub ----------------------Sub add(ByVal no1 As Integer, ByVal no2 As Integer, ByVal no3 As Integer) logic End Sub

IIF
Returns one of two objects, depending on the

evalution of expression. Its like Ternary operator in C or C++


IIF(Expression,Truepart,Falsepart)

Example
Dim salary As Integer =50000 Dim strAns as String strAns = IIF(salary>30000,Good,Bad) MsgBox(StrAns)

Split
Returns one-dimensional array containing a

specified number of sunstrings By default it splits using space


Usage
Split fullname and display parts in Textboxes

Example:

Dim TempA() As String = split(txtName.text, ,) txt1.text= TempA(0) txt2.text= TempA(1)

Join
Returns a string created by joining a number of

substrings contained in an array


Usage
Join all names in one text etc.

Example

Dim TempA() As String = {Hello,How,Are,You} txtJoin.text= Join(TempA, ,)

StrReverse(string)
Returns a string in which the character order of a

specified string is reversed


ASC(char)
Returns ASCII value for the input character

Chr(int)
Returns the character of that relative ASCII value

Shell
Runs an executable program Shell(path of Exe,Style of Open) Example
Dim ProcId as Integer ProcId=shell(notepad.exe,AppWinStyle.NormalFocus) SendKeys.Send(Hello Note)

AppWInStyle.Hide AppWinStyle.MinimizedFocus AppWinStyle.MaximizedFocus AppWinStyle.MinimizedNoFocus AppWinStyle.NormalFocus AppWinStyle.NormalNoFocus

Insert() Length() PadLeft() Compare() PadRight() Concat() Remove() Copy() Replace() Equals() Substring() Trim() EndsWith() StartsWith() Indexof() Ucase,Lcase,ToUpper,ToLower

Objective of MsgBox is to produce a pop-up message box, prompt the user and returns an integer indicating which button is clicked by user MsgBox and InputBox are inbuilt functions.
MsgBox(Prompt,Button+Icon Style,Title)

MsgBoxis the Model dialog box MsgBox returns an integer value. The value is determine by the type of buttons being clicked by the user.
(1-vbOk,2 vbCancel,3 vbAbort, 4 vbRetry,5 vbIgnore, 6 vbYes, 7 vbNo)

Its an advance version of MsgBox function MessageBox is the class and show is method of it Show method has more argument then MsgBox function. It have special argument for icon and button

MessageBox.Show(Text,caption,button,icon, default button,options,helpbutton)

InputBox function is to accept data from the user. An InputBox function will display a prompt box where the user can enter a value or a message in the form of text. The InputBox function with return a vlaue. We need to declare the data type for values to be accepted on the InputBox.

varName= InputBox(Prompt,Title,default_text,x-pos, y-pos)

Forms and dialog boxes are either modal or modeless. Modal dialog doesnt allow its parent window unless it is closed. A Modeless form allows the user to supply information and return to the previous task without closing the dialog box.
Dim frm as new frmModal Dim frmMl as new frmModeless frm.ShowDialog() For Modal Form frmMl.Show() For Modeless Form

Two(2) ways to share data


Using FormName.ControlName Using Public Variable

In Vb.Net there are two styles to provide user interface


Single- document interface(SDI) Multiple-document interface(MDI)

SDI means at a time single document of same application can open MDI allows to work with multiple documents with in single container form

Create new project or Existing Project, Add new form. Set the property of mainform
Name= frmMDI or frmMain Text= Main Form IsMDIContainer=true WindowState= Maximized (Set as StartUp form)

Create Child Form Set Property like


StartPosition= CenterParent FormBorderStyle=FixedSingle MaximizedBox=False ShowInTaskbar=False

Add menu control from MenuStrip


Give a name for menu Set ShortCuts and ImageIcon

Make a code for Each MenuItem


Dim frmMsg As new frmMessage frmMsg.MdiParent=Me frmMsg.show()

Can add ContextMenu control


Set Option ContextMenuStrip to each control

which you want to enable

What is Error ?
Error is somting that is unexpected.

Types of Error
Syntax (Design Time) Runtime Logical

Exception Handling is an in-built mechanism in .NET to detect and handle run time errors. Runtime errors are an expensive fact of life both during development and after release a software to customers. Errors take time to find and fix it The .NET framework contains lots of standard exceptions. The exceptions are arise during the execution of a program. It can be because of user, logic or system error.

If programmer do not provide any mechanism to handle these error the program goes to terminates. There are two way to trap Error
Structured Exception Handling (Newer) Unstructured Exception Handling (Older)

We use Try.......Catch......Finally statments. Catch and Finally blocks are optional All the exception are directly or indirectly inherited from the Exception Class. We can Catch all the exception using
Catch ex As Exception block

class is the base class of all exception class hirarchy. ex object of the class is used to access (error) the property of Exception class You can use catch for multiple exception
Exception

ex.ToString() will give the user a large

technical dump of the error that occurred like the error description with path of the form in which error will arise, line of the error, event name etc. ex.Message() Will give a more to the point error message. It display main moral of the error.

In Button Click Event..........


Try Dim intNo1,intNo2 As Integer, ans As Integer intNo1 = txtNo1.Text intNo2 = txtNo2.Text ans = intNo1+ intNo2 MsgBox(ans,Demo) Catch ex As Exception

MsgBox(ex.ToString,Error1) MsgBox(ex.Message,Error2)
Finally MsgBox(Hi i am at Finally part);

End Try

OutOfMemory Exception NullReference Exception InvalidCast Exception ArrayTypeMismatch Exception IndexOutOfRange Exception Arithmetic Exception DivideByZeroException OverFlowException FileNotFoundException DirectoryNotFoundException

UnStructured Exception are simple but now a days its obsolute in VB.NET programes There are three way to handle error
On Error GoTo <lableName> On Error Resume Next On Error GoTo 0 (Zero)

Component Object Model is an interface standard for software component introduced by Microsoft in 1993. It is used to enable inter process communication and dynamic object creation in any programming language that supports the technology. The term COM is often used in the software development industry as an umbrella term that encompasses the OLE, OLE Automation, ActiveX, COM+ and DCOM technologies.

DCOM is Distributed Component Object Model. It is the extension of the COM that allows COM components to communicate across the network boundaries. It can efficiently deploy and administrated
Its an open technology

DCOM communications also work between dissimilar computer hardware and OS

COM
COM stands for Component object model COM is on local or on one single machine COM is used for Desktop Applications COM is collection of tools which are executed on client side environment COM Components exposes its interfaces at interface pointer where client access Components interface

DCOM
Distributed component object model DCOM is a working across several machines DCOM is used Network based Applications DCOM is a Distributed component object Model runs at the given server DCOM is the protocol which enables the s/w components in different machine to communicate with each other through n/w

Managed Code is what Visual Basic .NET and C# compilers create. The code, which is developed in .NET framework, is known as managed code. This code is directly executed by CLR with help of managed code execution. Any language that is written in .NET Framework is managed code. Managed code uses CLR which in turns looks after your applications by managing memory, handling security, allowing cross - language debugging, and so on.

The code, which is developed outside .NET, Framework is known as unmanaged code. Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level functions of the operating system. Background compatibility with code of VB, ASP and COM are examples of unmanaged code.

Unmanaged code can be unmanaged source code and unmanaged compile code. Unmanaged code is executed with help of wrapper classes. Wrapper classes are of two types: CCW (COM Callable Wrapper) and RCW (Runtime Callable Wrapper).

Anda mungkin juga menyukai